forked from sssssyf/SSMLP-RPL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
102 lines (85 loc) · 2.94 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
97
98
99
100
101
102
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)
if criterion:
weights = criterion.state_dict()
filename = '{}/checkpoints/{}_{}_criterion.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(networks, result_dir, name='', loss='', criterion=None):
weights = networks.state_dict()
filename = '{}/checkpoints/{}_{}.pth'.format(result_dir, name, loss)
networks.load_state_dict(torch.load(filename))
if criterion:
weights = criterion.state_dict()
filename = '{}/checkpoints/{}_{}_criterion.pth'.format(result_dir, name, loss)
criterion.load_state_dict(torch.load(filename))
return networks, criterion