-
Notifications
You must be signed in to change notification settings - Fork 745
Expand file tree
/
Copy pathplot.py
More file actions
236 lines (198 loc) · 6.79 KB
/
plot.py
File metadata and controls
236 lines (198 loc) · 6.79 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
import os
import sys
try:
# pydot-ng is a fork of pydot that is better maintained.
import pydot_ng as pydot
except ImportError:
# pydotplus is an improved version of pydot
try:
import pydotplus as pydot
except ImportError:
# Fall back on pydot if necessary.
try:
import pydot
except ImportError:
pydot = None
def check_pydot():
"""Returns True if PyDot is available."""
return pydot is not None
def check_graphviz():
"""Returns True if both PyDot and Graphviz are available."""
if not check_pydot():
return False
try:
# Attempt to create an image of a blank graph
# to check the pydot/graphviz installation.
pydot.Dot.create(pydot.Dot())
return True
except (OSError, pydot.InvocationException):
return False
def add_edge(dot, src, dst):
if not dot.get_edge(src, dst):
dot.add_edge(pydot.Edge(src, dst))
def add_edge_node(dot, node, next_node):
if node['type'] == "sequential":
for i in range(len(node['nodes']) - 1):
add_edge_node(dot, node['nodes'][i], node['nodes'][i + 1])
add_edge_node(dot, node['nodes'][-1], next_node)
elif node['type'] == "nest":
for i in range(len(node['nodes'])):
add_edge_node(dot, node['nodes'][i], next_node)
elif next_node['type'] == "sequential":
for i in range(len(next_node['nodes']) - 1):
add_edge_node(dot, node, next_node['nodes'][i])
add_edge_node(dot, node, next_node['nodes'][0])
elif next_node['type'] == "nest":
for i in range(len(next_node['nodes'])):
add_edge_node(dot, node, next_node['nodes'][i])
else:
add_edge(dot, node['id'], next_node['id'])
def make_node(id):
return {"id": id, "type": "node"}
def model_to_dot(
model,
subgraph=False,
dpi=96,
depth=4,
):
if not model.built:
raise ValueError(
"This model has not yet been built. "
"Build the model first by calling `build()` or by calling "
"the model on a batch of data."
)
from tf_agents.networks import NestMap
from tf_agents.networks import NestFlatten
from tf_agents.networks import sequential
if not check_pydot():
raise ImportError(
"You must install pydot (`pip install pydot`) for "
"model_to_dot to work."
)
if subgraph:
dot = pydot.Cluster(style="dashed", graph_name=model.name)
dot.set("label", model.name)
dot.set("labeljust", "l")
else:
dot = pydot.Dot()
dot.set("rankdir", "TB")
dot.set("dpi", dpi)
dot.set_node_defaults(shape="record")
layers = model.layers
listIdNode = {"nodes": [], "type": (
"nest" if isinstance(model, NestMap) else "sequential")}
# Create graph nodes.
for layer in layers:
layer_id = str(id(layer))
# Append a wrapped layer's label to node's label, if it exists.
layer_name = layer.name
class_name = layer.__class__.__name__
# Create node's label.
label = "{0}|{1}".format(class_name, layer_name)
def format_shape(shape):
return (
str(shape)
.replace(str(None), "None")
.replace("{", r"\{")
.replace("}", r"\}")
)
try:
outputlabels = format_shape(layer.output_shape)
except AttributeError:
outputlabels = "?"
if hasattr(layer, "input_shape"):
inputlabels = format_shape(layer.input_shape)
elif hasattr(layer, "input_shapes"):
inputlabels = ", ".join(
[format_shape(ishape) for ishape in layer.input_shapes]
)
else:
inputlabels = "?"
label = "{%s}|{input:|output:}|{{%s}|{%s}}" % (
label,
inputlabels,
outputlabels,
)
if depth == 0:
listIdNode['nodes'].append(make_node(layer_id))
node = pydot.Node(layer_id, label=label)
dot.add_node(node)
continue
if isinstance(layer, sequential.Sequential) or isinstance(layer, NestMap):
submodel_wrapper, sub_listIdNode = model_to_dot(
layer, subgraph=True, dpi=dpi, depth=depth-1)
listIdNode['nodes'].append(sub_listIdNode)
dot.add_subgraph(submodel_wrapper)
else:
listIdNode['nodes'].append(make_node(layer_id))
node = pydot.Node(layer_id, label=label)
dot.add_node(node)
# Add edges between nodes.
if not subgraph and isinstance(model, sequential.Sequential):
for i in range(len(listIdNode['nodes']) - 1):
node = listIdNode['nodes'][i]
next_node = listIdNode['nodes'][i + 1]
add_edge_node(dot, node, next_node)
return dot, listIdNode
def print_msg(message, line_break=True):
if line_break:
sys.stdout.write(message + "\n")
else:
sys.stdout.write(message)
sys.stdout.flush()
def path_to_string(path):
if isinstance(path, os.PathLike):
return os.fspath(path)
return path
def plot_model(
model,
to_file="model.png",
subgraph=False,
dpi=96,
depth=4,
):
if not model.built:
raise ValueError(
"This model has not yet been built. "
"Build the model first by calling `build()` or by calling "
"the model on a batch of data."
)
if not check_graphviz():
message = (
"You must install pydot (`pip install pydot`) "
"and install graphviz "
"(see instructions at https://graphviz.gitlab.io/download/) "
"for plot_model to work."
)
if "IPython.core.magics.namespace" in sys.modules:
# We don't raise an exception here in order to avoid crashing
# notebook tests where graphviz is not available.
print_msg(message)
return
else:
raise ImportError(message)
dot, _ = model_to_dot(
model,
subgraph=subgraph,
dpi=dpi,
depth=depth,
)
to_file = path_to_string(to_file)
if dot is None:
return
_, extension = os.path.splitext(to_file)
if not extension:
extension = "png"
else:
extension = extension[1:]
# Save image to disk.
dot.write(to_file, format=extension)
# Return the image as a Jupyter Image object, to be displayed in-line.
# Note that we cannot easily detect whether the code is running in a
# notebook, and thus we always return the Image if Jupyter is available.
if extension != "pdf":
try:
from IPython import display
return display.Image(filename=to_file)
except ImportError:
pass