-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
42 lines (29 loc) · 893 Bytes
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import os
import json
class AverageMeter(object):
"""Computes and stores the average and current value.
Code imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262
"""
def __init__(self):
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 read_json(fpath):
with open(fpath, 'r') as f:
obj = json.load(f)
return obj
def mkdir_if_missing(directory):
if not os.path.exists(directory):
os.makedirs(directory)
def write_json(obj, fpath):
mkdir_if_missing(os.path.dirname(fpath))
with open(fpath, 'w') as f:
json.dump(obj, f, indent=4, separators=(',', ': '))