python中的ProgressMeter类【自定义】
显示进度条
# 1.定义类ProgressMeter
class ProgressMeter(object):
def __init__(self, num_batches, *meters):
# 初始化头,如:[ 100/2500](占符号位)
self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
self.meters = meters
self.prefix = ""
# 每个批量的打印结果
def pr2int(self, batch):
entries = [self.prefix + self.batch_fmtstr.format(batch)]
# 每个格外变量的打印,拼接为向量
entries += [str(meter) for meter in self.meters]
# 将向量用\t再拼接为字符串
print('\t'.join(entries))
def _get_batch_fmtstr(self, num_batches):
# 如:[ 100/2500]
# 批量大小的符号位
num_digits = len(str(num_batches // 1))
fmt = '{:' + str(num_digits) + 'd}'
return '[' + fmt + '/' + fmt.format(num_batches) + ']'
# 2.使用
batch_time = AverageMeter('Time', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('Acc@1', ':6.2f')
# len(train_loader): 批量数
# batch_time: 每批计算所用时长
# losses: 所有损失
# top1:这批的准确率
progress = ProgressMeter(len(train_loader), batch_time, losses, top1)
# 打印结果
if i % 100 == 0:
progress.pr2int(i)