forked from carpedm20/ENAS-pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
276 lines (210 loc) · 7.41 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
from __future__ import print_function
from collections import defaultdict
import collections
from datetime import datetime
import os
import json
import logging
import numpy as np
import pygraphviz as pgv
import torch
from torch.autograd import Variable
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
try:
import scipy.misc
imread = scipy.misc.imread
imresize = scipy.misc.imresize
imsave = imwrite = scipy.misc.imsave
except:
import cv2
imread = cv2.imread
imresize = cv2.imresize
imsave = imwrite = cv2.imwrite
##########################
# Network visualization
##########################
def add_node(graph, node_id, label, shape='box', style='filled'):
if label.startswith('x'):
color = 'white'
elif label.startswith('h'):
color = 'skyblue'
elif label == 'tanh':
color = 'yellow'
elif label == 'ReLU':
color = 'pink'
elif label == 'identity':
color = 'orange'
elif label == 'sigmoid':
color = 'greenyellow'
elif label == 'avg':
color = 'seagreen3'
else:
color = 'white'
if not any(label.startswith(word) for word in ['x', 'avg', 'h']):
label = f"{label}\n({node_id})"
graph.add_node(
node_id, label=label, color='black', fillcolor=color,
shape=shape, style=style,
)
def draw_network(dag, path):
makedirs(os.path.dirname(path))
graph = pgv.AGraph(directed=True, strict=True,
fontname='Helvetica', arrowtype='open') # not work?
checked_ids = [-2, -1, 0]
if -1 in dag:
add_node(graph, -1, 'x[t]')
if -2 in dag:
add_node(graph, -2, 'h[t-1]')
add_node(graph, 0, dag[-1][0].name)
for idx in dag:
for node in dag[idx]:
if node.id not in checked_ids:
add_node(graph, node.id, node.name)
checked_ids.append(node.id)
graph.add_edge(idx, node.id)
graph.layout(prog='dot')
graph.draw(path)
def make_gif(paths, gif_path, max_frame=50, prefix=""):
import imageio
paths.sort()
skip_frame = len(paths) // max_frame
paths = paths[::skip_frame]
images = [imageio.imread(path) for path in paths]
max_h, max_w, max_c = np.max(
np.array([image.shape for image in images]), 0)
for idx, image in enumerate(images):
h, w, c = image.shape
blank = np.ones([max_h, max_w, max_c], dtype=np.uint8) * 255
pivot_h, pivot_w = (max_h-h)//2, (max_w-w)//2
blank[pivot_h:pivot_h+h,pivot_w:pivot_w+w,:c] = image
images[idx] = blank
try:
images = [Image.fromarray(image) for image in images]
draws = [ImageDraw.Draw(image) for image in images]
font = ImageFont.truetype("assets/arial.ttf", 30)
steps = [int(os.path.basename(path).rsplit('.', 1)[0].split('-')[1]) for path in paths]
for step, draw in zip(steps, draws):
draw.text((max_h//20, max_h//20),
f"{prefix}step: {format(step, ',d')}", (0, 0, 0), font=font)
except IndexError:
pass
imageio.mimsave(gif_path, [np.array(img) for img in images], duration=0.5)
##########################
# Torch
##########################
def detach(h):
if type(h) == Variable:
return Variable(h.data)
else:
return tuple(detach(v) for v in h)
def get_variable(inputs, cuda=False, **kwargs):
if type(inputs) in [list, np.ndarray]:
inputs = torch.Tensor(inputs)
if cuda:
out = Variable(inputs.cuda(), **kwargs)
else:
out = Variable(inputs, **kwargs)
return out
def update_lr(optimizer, lr):
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def batchify(data, bsz, use_cuda):
# code from https://github.com/pytorch/examples/blob/master/word_language_model/main.py
nbatch = data.size(0) // bsz
data = data.narrow(0, 0, nbatch * bsz)
data = data.view(bsz, -1).t().contiguous()
if use_cuda:
data = data.cuda()
return data
##########################
# ETC
##########################
Node = collections.namedtuple('Node', ['id', 'name'])
class keydefaultdict(defaultdict):
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
else:
ret = self[key] = self.default_factory(key)
return ret
def to_item(x):
"""Converts x, possibly scalar and possibly tensor, to a Python scalar."""
if isinstance(x, (float, int)):
return x
if float(torch.__version__[0:3]) < 0.4:
assert (x.dim() == 1) and (len(x) == 1)
return x[0]
return x.item()
def get_logger(name=__file__, level=logging.INFO):
logger = logging.getLogger(name)
if getattr(logger, '_init_done__', None):
logger.setLevel(level)
return logger
logger._init_done__ = True
logger.propagate = False
logger.setLevel(level)
formatter = logging.Formatter("%(asctime)s:%(levelname)s::%(message)s")
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(0)
del logger.handlers[:]
logger.addHandler(handler)
return logger
logger = get_logger()
def prepare_dirs(args):
"""Sets the directories for the model, and creates those directories.
Args:
args: Parsed from `argparse` in the `config` module.
"""
if args.load_path:
if args.load_path.startswith(args.log_dir):
args.model_dir = args.load_path
else:
if args.load_path.startswith(args.dataset):
args.model_name = args.load_path
else:
args.model_name = "{}_{}".format(args.dataset, args.load_path)
else:
args.model_name = "{}_{}".format(args.dataset, get_time())
if not hasattr(args, 'model_dir'):
args.model_dir = os.path.join(args.log_dir, args.model_name)
args.data_path = os.path.join(args.data_dir, args.dataset)
for path in [args.log_dir, args.data_dir, args.model_dir]:
if not os.path.exists(path):
makedirs(path)
def get_time():
return datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
def save_args(args):
param_path = os.path.join(args.model_dir, "params.json")
logger.info("[*] MODEL dir: %s" % args.model_dir)
logger.info("[*] PARAM path: %s" % param_path)
with open(param_path, 'w') as fp:
json.dump(args.__dict__, fp, indent=4, sort_keys=True)
def save_dag(args, dag, name):
save_path = os.path.join(args.model_dir, name)
logger.info("[*] Save dag : {}".format(save_path))
json.dump(dag, open(save_path, 'w'))
def load_dag(args):
load_path = os.path.join(args.dag_path)
logger.info("[*] Load dag : {}".format(load_path))
with open(load_path) as f:
dag = json.load(f)
dag = {int(k): [Node(el[0], el[1]) for el in v] for k, v in dag.items()}
save_dag(args, dag, "dag.json")
draw_network(dag, os.path.join(args.model_dir, "dag.png"))
return dag
def makedirs(path):
if not os.path.exists(path):
logger.info("[*] Make directories : {}".format(path))
os.makedirs(path)
def remove_file(path):
if os.path.exists(path):
logger.info("[*] Removed: {}".format(path))
os.remove(path)
def backup_file(path):
root, ext = os.path.splitext(path)
new_path = "{}.backup_{}{}".format(root, get_time(), ext)
os.rename(path, new_path)
logger.info("[*] {} has backup: {}".format(path, new_path))