# torchnet.meter使用记录

## 1、自定义类实现平均

import torch
import numpy as np

class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name):
self.name = name
self.reset()

def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0

def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count

def __str__(self):
format_str = (f"%s: avg=%s, val=%s, count=%s") % (
self.name, str(self.avg), str(self.val), str(self.count))
return format_str

1）单值调用

losses = AverageMeter("Loss")
for i in range(10):
losses.update(i + 5, 1)
# print(losses.val, losses.avg, losses.count)
print(losses)

2）多值调用

losses = AverageMeter("Loss")
losses.reset()
for i in range(10):
losses.update(np.array([1, 3 + i]), 1)
# print(str(losses.val), losses.avg, losses.count)
print(losses)

## 2、torchnet.meter包使用

### 2.1、AverageValueMeter

from torchnet import meter

loss_meter = meter.AverageValueMeter()
loss_meter.reset()
for i in range(10):
print(loss_meter.value()) # mean, std

05-16 3427

12-10 1588
10-02 5802
09-15 1898
12-05 1万+
10-03 1003
02-18 1万+
01-10 849
10-24 3298