-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.py
executable file
·96 lines (79 loc) · 2.71 KB
/
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import os
import sys
import errno
import os.path as osp
import numpy as np
import torch
def mkdir_if_missing(directory):
if not osp.exists(directory):
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise
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
class Logger(object):
"""
Write console output to external text file.
Code imported from https://github.com/Cysu/open-reid/blob/master/reid/utils/logging.py.
"""
def __init__(self, fpath=None):
self.console = sys.stdout
self.file = None
if fpath is not None:
mkdir_if_missing(os.path.dirname(fpath))
self.file = open(fpath, 'w')
def __del__(self):
self.close()
def __enter__(self):
pass
def __exit__(self, *args):
self.close()
def write(self, msg):
self.console.write(msg)
if self.file is not None:
self.file.write(msg)
def flush(self):
self.console.flush()
if self.file is not None:
self.file.flush()
os.fsync(self.file.fileno())
def close(self):
self.console.close()
if self.file is not None:
self.file.close()
def save_networks(networks, result_dir, name='', loss='', criterion=None):
mkdir_if_missing(osp.join(result_dir, 'checkpoints'))
weights = networks.state_dict()
filename = '{}/checkpoints/{}_{}.pth'.format(result_dir, name, loss)
torch.save(weights, filename)
def save_GAN(netG, netD, result_dir, name=''):
mkdir_if_missing(osp.join(result_dir, 'checkpoints'))
weights = netG.state_dict()
filename = '{}/{}_G.pth'.format(result_dir, name)
torch.save(weights, filename)
weights = netD.state_dict()
filename = '{}/{}_D.pth'.format(result_dir, name)
torch.save(weights, filename)
def load_networks(net1, net2, dataset, split):
weights = net1.state_dict()
filename1 = './log/models/{}/checkpoints/classifier32_ARPLoss_{}{}_.pth'.format(dataset, split, '1')
filename2 = './log/models/{}/checkpoints/classifier32_ARPLoss_{}{}_.pth'.format(dataset, split, '2')
net1.load_state_dict(torch.load(filename1))
net2.load_state_dict(torch.load(filename2))
return net1, net2