Computes and stores the average and current value
| 20 | |
| 21 | |
| 22 | class AverageMeter(object): |
| 23 | """Computes and stores the average and current value""" |
| 24 | |
| 25 | def __init__(self, length=0): |
| 26 | self.length = length |
| 27 | self.reset() |
| 28 | |
| 29 | def reset(self): |
| 30 | if self.length > 0: |
| 31 | self.history = [] |
| 32 | else: |
| 33 | self.count = 0 |
| 34 | self.sum = 0.0 |
| 35 | self.val = 0.0 |
| 36 | self.avg = 0.0 |
| 37 | |
| 38 | def reduce_update(self, tensor, num=1): |
| 39 | link.allreduce(tensor) |
| 40 | self.update(tensor.item(), num=num) |
| 41 | |
| 42 | def update(self, val, num=1): |
| 43 | if self.length > 0: |
| 44 | # currently assert num==1 to avoid bad usage, refine when there are some explict requirements |
| 45 | assert num == 1 |
| 46 | self.history.append(val) |
| 47 | if len(self.history) > self.length: |
| 48 | del self.history[0] |
| 49 | |
| 50 | self.val = self.history[-1] |
| 51 | self.avg = np.mean(self.history) |
| 52 | else: |
| 53 | self.val = val |
| 54 | self.sum += val*num |
| 55 | self.count += num |
| 56 | self.avg = self.sum / self.count |
| 57 | |
| 58 | |
| 59 | def makedir(path): |