如何让tqdm在循环结束时优雅打印批次平均精度/损失?
用tqdm优雅打印批次平均精度/损失的方法
方法1:结合累加计算与postfix实时更新
不需要额外保存所有批次的精度、损失数据,只需在循环中维护累加值和批次计数,通过set_postfix实时展示当前批次和累计均值,循环结束后用write在同一行输出最终结果:
from tqdm import tqdm import numpy as np total_loss = 0.0 total_acc = 0.0 num_batches = 100 pbar = tqdm(range(num_batches)) for batch_idx in pbar: # 模拟当前批次的loss和acc计算 current_loss = np.random.uniform(0.1, 0.5) current_acc = np.random.uniform(0.8, 0.95) # 累加计算 total_loss += current_loss total_acc += current_acc avg_loss = total_loss / (batch_idx + 1) avg_acc = total_acc / (batch_idx + 1) # 更新进度条后缀信息 pbar.set_postfix({ '当前损失': f'{current_loss:.4f}', '当前精度': f'{current_acc:.4f}', '平均损失': f'{avg_loss:.4f}', '平均精度': f'{avg_acc:.4f}' }) # 循环结束后输出最终均值 pbar.write(f'最终结果:平均损失={total_loss/num_batches:.4f},平均精度={total_acc/num_batches:.4f}')
方法2:动态更新进度条描述文本
如果更关注最终均值的输出,也可以在循环中仅展示当前批次信息,最后用write输出累计均值:
from tqdm import tqdm import numpy as np total_loss = 0.0 total_acc = 0.0 num_batches = 100 with tqdm(range(num_batches), desc='训练批次') as pbar: for batch_idx in pbar: current_loss = np.random.uniform(0.1, 0.5) current_acc = np.random.uniform(0.8, 0.95) total_loss += current_loss total_acc += current_acc # 更新进度条描述,展示当前批次数据 pbar.set_description(f'训练批次 | 当前损失:{current_loss:.4f} | 当前精度:{current_acc:.4f}') # 输出最终累计均值 pbar.write(f'训练完成 | 平均损失:{total_loss/num_batches:.4f} | 平均精度:{total_acc/num_batches:.4f}')
核心优势
- 无需存储所有批次的精度、损失数据,仅维护累加值和计数,节省内存开销
- 利用tqdm原生方法
set_postfix、set_description、write实现,不破坏进度条的输出格式 - 最终均值与进度条输出在同一行区域,保持日志的整洁性
内容的提问来源于stack exchange,提问作者ChaosPredictor
相关产品推荐
相关产品推荐

