-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathvisualization.py
More file actions
299 lines (248 loc) · 10.2 KB
/
visualization.py
File metadata and controls
299 lines (248 loc) · 10.2 KB
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import matplotlib.pyplot as plt
import graphviz
import deep_architect.core as co
import deep_architect.utils as ut
import deep_architect.searchers as se
import numpy as np
def running_max(vs):
return np.maximum.accumulate(vs)
def draw_graph(outputs,
draw_hyperparameters=True,
draw_io_labels=True,
draw_module_hyperparameter_info=True,
out_folderpath=None,
graph_name='graph',
print_to_screen=True):
"""Draws a graph representation of the current state of the search space.
All edges are directed. An edge between two modules represents the output of
the first module going into the input of the second module. An edge between
a module and an hyperparameter represents the dependency of that module on
that hyperparameter.
This visualization functionality is useful to verify that the description of
the search space done through the domain-specific language encodes the
intended search space.
.. note::
All drawing options are set to `True` to give a sense of all the
information that can be displayed simultaneously. This can lead to
cluttered graphs and slow rendering. We recommend changing the defaults
according to the desired behavior.
For generating a representation for a fully specified model,
we recommend setting `draw_hyperparameters` to `False`, as if we are
only concerned with the resulting model, the sharing structure of
hyperparameters does not really matter. We recommend using
`draw_hyperparameters` set to `True` when the user wishes to visualize
the hyperparameter sharing pattern, e.g., to verify that it has been
implemented correctly.
Args:
outputs (dict[str, deep_architect.core.Output]): Dictionary of named
outputs from which we can reach all the modules in the search space
by backwards traversal.
draw_hyperparameters (bool, optional): Draw hyperparameter nodes in the
graph, representing the dependencies between hyperparameters and
modules.
draw_io_labels (bool, optional): If `True`,
draw edge labels connecting different modules
with the local names of the input and output that are being connected.
draw_module_hyperparameter_info (bool, optional): If `True`,
draw the hyperparameters of a module alongside the module.
graph_name (str, optional): Name of the file used to store the
rendered graph. Only needs to be provided if we desire to output
the graph to a file, rather than just show it.
out_folderpath (str, optional): Folder to which to store the PDF file with
the rendered graph. If no path is provided, no file is created.
print_to_screen (bool, optional): Shows the result of rendering the
graph directly to screen.
"""
assert print_to_screen or out_folderpath is not None
g = graphviz.Digraph()
edge_fs = '10'
h_fs = '10'
penwidth = '1'
def _draw_connected_input(ix_localname, ix):
ox = ix.get_connected_output()
if not draw_io_labels:
label = ''
else:
ox_localname = None
for ox_iter_localname, ox_iter in ox.get_module().outputs.items():
if ox_iter == ox:
ox_localname = ox_iter_localname
break
assert ox_localname is not None
label = ix_localname + ':' + ox_localname
g.edge(ox.get_module().get_name(),
ix.get_module().get_name(),
label=label,
fontsize=edge_fs)
def _draw_unconnected_input(ix_localname, ix):
g.node(ix.get_name(),
shape='invhouse',
penwidth=penwidth,
fillcolor='firebrick',
style='filled')
g.edge(ix.get_name(), ix.get_module().get_name())
def _draw_module_hyperparameter(m, h_localname, h):
if h.has_value_assigned():
label = h_localname + '=' + str(h.get_value())
else:
label = h_localname
g.edge(h.get_name(), m.get_name(), label=label, fontsize=edge_fs)
def _draw_dependent_hyperparameter_relations(h_dep):
for h_localname, h in h_dep._hyperps.items():
if h.has_value_assigned():
label = h_localname + '=' + str(h.get_value())
else:
label = h_localname
g.edge(h.get_name(),
h_dep.get_name(),
label=label,
fontsize=edge_fs)
def _draw_module_hyperparameter_info(m):
g.node(
m.get_name(),
xlabel="<" + '<br align="right"/>'.join([
'<FONT POINT-SIZE="%s">' % h_fs + h_localname +
('=' + str(h.get_value()) if h.has_value_assigned() else '') +
"</FONT>" for h_localname, h in m.hyperps.items()
]) + ">")
def _draw_output_terminal(ox_localname, ox):
g.node(ox.get_name(),
shape='house',
penwidth=penwidth,
fillcolor='deepskyblue',
style='filled')
g.edge(ox.get_module().get_name(), ox.get_name())
nodes = set()
def fn(m):
"""Adds the module information to the graph that is local to the module.
"""
nodes.add(m.get_name())
for ix_localname, ix in m.inputs.items():
if ix.is_connected():
_draw_connected_input(ix_localname, ix)
else:
_draw_unconnected_input(ix_localname, ix)
if draw_hyperparameters:
for h_localname, h in m.hyperps.items():
_draw_module_hyperparameter(m, h_localname, h)
if draw_module_hyperparameter_info:
_draw_module_hyperparameter_info(m)
return False
# generate most of the graph.
co.traverse_backward(outputs, fn)
# drawing the hyperparameter graph.
if draw_hyperparameters:
hs = co.get_all_hyperparameters(outputs)
for h in hs:
if isinstance(h, co.DependentHyperparameter):
_draw_dependent_hyperparameter_relations(h)
g.node(h.get_name(),
fontsize=h_fs,
fillcolor='darkseagreen',
style='filled')
# add the output terminals.
for m in co.extract_unique_modules(list(outputs.values())):
for ox_localname, ox in m.outputs.items():
_draw_output_terminal(ox_localname, ox)
# minor adjustments to attributes.
for s in nodes:
g.node(s,
shape='rectangle',
penwidth=penwidth,
fillcolor='goldenrod',
style='filled')
if print_to_screen or out_folderpath is not None:
g.render(graph_name, out_folderpath, view=print_to_screen, cleanup=True)
def draw_graph_evolution(outputs,
hyperp_value_lst,
out_folderpath,
graph_name='graph',
draw_hyperparameters=True,
draw_io_labels=True,
draw_module_hyperparameter_info=True):
def draw_fn(i):
return draw_graph(
outputs,
draw_hyperparameters=draw_hyperparameters,
draw_io_labels=draw_io_labels,
draw_module_hyperparameter_info=draw_module_hyperparameter_info,
out_folderpath=out_folderpath,
graph_name=graph_name + '-%d' % i,
print_to_screen=False)
draw_fn(0)
h_iter = co.unassigned_independent_hyperparameter_iterator(outputs)
for i, v in enumerate(hyperp_value_lst):
h = next(h_iter)
h.assign_value(v)
draw_fn(i + 1)
filepath_lst = [
ut.join_paths([out_folderpath, graph_name + '-%d.pdf' % i])
for i in range(len(hyperp_value_lst) + 1)
]
out_filepath = ut.join_paths([out_folderpath, graph_name + '.pdf'])
cmd = " ".join(["pdftk"] + filepath_lst + ["cat", "output", out_filepath])
ut.run_bash_command(cmd)
for fp in filepath_lst:
ut.delete_file(fp)
class LinePlot:
def __init__(self, title=None, xlabel=None, ylabel=None):
self.data = []
self.title = title
self.xlabel = xlabel
self.ylabel = ylabel
self.color_to_str = {'black': 'k', 'red': 'r'}
self.line_type_to_str = {'solid': '-', 'dotted': ':', 'dashed': '--'}
def add_line(self, xs, ys, label=None, err=None, color=None,
line_type=None):
d = {
"xs": xs,
"ys": ys,
"label": label,
"err": err,
"color": color,
"line_type": line_type
}
self.data.append(d)
def plot(self, show=True, fpath=None):
f = plt.figure()
for d in self.data:
fmt = (self.color_to_str.get(d['color'], '') +
self.line_type_to_str.get(d['line_type'], ''))
plt.errorbar(d['xs'],
d['ys'],
yerr=d['err'],
label=d['label'],
fmt=fmt)
if self.title is not None:
plt.title(self.title)
if self.xlabel is not None:
plt.xlabel(self.xlabel)
if self.ylabel is not None:
plt.ylabel(self.ylabel)
if any([d['label'] is not None for d in self.data]):
plt.legend(loc='best')
if fpath is not None:
f.savefig(fpath, bbox_inches='tight')
if show:
plt.show()
return f
def visualize_model_as_text(inputs, outputs):
def show(d, indent, sep):
for k in sorted(d):
print("%s%s%s%s" % (" " * indent, k, sep, d[k]))
d = co.jsonify(inputs, outputs)
print("=" * 32)
print("I)")
show(d["unconnected_inputs"], 2, " : ")
print("O)")
show(d["unconnected_outputs"], 2, " : ")
name_to_module = d["modules"]
print("=" * 32)
for module_name in d["module_eval_seq"]:
m = name_to_module[module_name]
print(m["module_name"])
print(" H)")
show(m["hyperp_name_to_val"], 4, " = ")
print(" C)")
show(m["in_connections"], 4, " <= ")
print("=" * 32)