-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmainVisualize.lua
More file actions
347 lines (323 loc) · 11.3 KB
/
Copy pathmainVisualize.lua
File metadata and controls
347 lines (323 loc) · 11.3 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
----------------------------------------------------------------------
--
-- Deep time series learning: Analysis of Torch
--
-- Visualization functions
--
----------------------------------------------------------------------
----------------------------------------------------------------------
-- Imports
require 'image'
require 'torch'
local uuid = require 'uuid'
local json = require 'cjson'
Plot = require 'itorch.Plot'
visualMonitor = torch.class('visualMonitor');
function visualMonitor:__init(file, type)
self.file = file or 'monitor.html'
self.type = type or 'full'
self.monitorModules = {} -- Modules that we are monitoring
self.state = {'idle'}; -- States of monitoring (idle, pretrain, train, finetuning)
self.plotTables = {} -- Check the learning state
end
function visualMonitor:refresh()
self:render();
-- Here need to send refresh request
os.execute('refresh_state ' .. pid .. '')
end
function visualMonitor:registerModule(module, description)
-- Create a structure to monitor
monitored = {};
monitored.module = module;
monitored.description = description;
-- Here we simply add the structure to monitoring list
table.insert(self.monitorModules, monitored)
end
function visualMonitor:state()
end
function visualMonitor:open()
os.execute('open ' .. file);
end
local function encodeAllModels(m)
local s = json.encode(m)
local w = {'selected', 'above', 'geometries', 'right', 'tags'}
for i=1,#w do
local before = '"' .. w[i] .. '":{}'
local after = '"' .. w[i] .. '":[]'
s=string.gsub(s, before, after)
end
return s
end
function visualMonitor:render()
local gen_divs = '';
local gen_models = '';
local modelDefinition = [[if(typeof(Bokeh) !== "undefined") {
console.log("Bokeh: BokehJS loaded, going straight to plotting");
var modelid = "${model_id}";
var modeltype = "Plot";
var all_models = ${all_models};
Bokeh.load_models(all_models);
var model = Bokeh.Collections(modeltype).get(modelid);
$("#${window_id}").html(''); // clear any previous plot in window_id
var view = new model.default_view({model: model, el: "#${window_id}"});
} else {
load_lib(bokehjs_url, function() {
console.log("Bokeh: BokehJS plotting callback run at", new Date())
var modelid = "${model_id}";
var modeltype = "Plot";
var all_models = ${all_models};
Bokeh.load_models(all_models);
var model = Bokeh.Collections(modeltype).get(modelid);
$("#${window_id}").html(''); // clear any previous plot in window_id
var view = new model.default_view({model: model, el: "#${window_id}"});
}); }]]
local divDefinition = [[<div class="plotdiv" id="${div_id}" style="float:left; width:250px; height:220px; margin-left:0px ; margin-top:0px"></div>]]
for i = 1,#plotsTable do
print(i);
local allmodels = plotsTable[i]:_toAllModels()
local div_id = uuid.new()
local window_id = window_id or div_id
plotsTable[i]._winid = window_id
-- find model_id
local model_id
for k,v in ipairs(allmodels) do
if v.type == 'Plot' then
model_id = v.id
v.attributes.plot_width = 200;
v.attributes.plot_height = 200;
v.attributes.logo = 'None'
v.attributes.toolbar_location = 'None'
v.attributes.title_font_size = '1pt'
v.attributes.min_border = 0;
v.attributes.border_left = 0;
v.attributes.border_right = 0;
v.attributes.border_up = 0;
v.attributes.border_down = 0;
end
end
assert(model_id, "Could not find Plot element in input allmodels");
local html = modelDefinition % {
window_id = window_id,
div_id = div_id,
all_models = encodeAllModels(allmodels),
model_id = model_id
};
local div = divDefinition % {
div_id = div_id
};
gen_models = gen_models .. html
gen_divs = gen_divs .. div
end
local base_template = [[ <script type="text/javascript">
$(function() {
if (typeof (window._bokeh_onload_callbacks) === "undefined"){ window._bokeh_onload_callbacks = []; }
function load_lib(url, callback) { window._bokeh_onload_callbacks.push(callback);
if (window._bokeh_is_loading){ console.log("Bokeh: BokehJS is being loaded, scheduling callback at", new Date()); return null; }
console.log("Bokeh: BokehJS not loaded, scheduling load and callback at", new Date());
window._bokeh_is_loading = true;
var s = document.createElement('script'); s.src = url; s.async = true;
s.onreadystatechange = s.onload = function(){
Bokeh.embed.inject_css("https://cdn.pydata.org/bokeh-0.7.0.min.css");
window._bokeh_onload_callbacks.forEach(function(callback){callback()});
};
s.onerror = function() { console.warn("failed to load library " + url); };
document.getElementsByTagName("head")[0].appendChild(s);
}
bokehjs_url = "https://cdn.pydata.org/bokeh-0.7.0.min.js"
]] .. gen_models .. [[
});
</script>
]]
local html =
[[ <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.pydata.org/bokeh-0.7.0.min.css" type="text/css" />
<script type="text/javascript" src="https://cdn.pydata.org/bokeh-0.7.0.js"></script> ]]
.. base_template ..
[[ </head>
<body> ]]
.. gen_divs ..
[[ </body>
</html> ]]
return html
end
function plotTimeSeries(y)
print(y);
plot = Plot();
-- Generate an index vector
x = torch.linspace(1, y:size(1), y:size(1));
plot:line(x, y, 'red', 'time series')
plot:legend(true)
plot:title('Line Plot Demo')
plot:draw()
plot:save('fig.html');
os.execute('open fig.html');
end
function generateHTMLColor()
htmlCodes = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
color = '#'
for i = 1,6 do
color = color .. htmlCodes[math.random(#htmlCodes)];
end
return color;
end
function multiPlot(plotsTable)
local gen_divs = '';
local gen_models = '';
local modelDefinition = [[if(typeof(Bokeh) !== "undefined") {
console.log("Bokeh: BokehJS loaded, going straight to plotting");
var modelid = "${model_id}";
var modeltype = "Plot";
var all_models = ${all_models};
Bokeh.load_models(all_models);
var model = Bokeh.Collections(modeltype).get(modelid);
$("#${window_id}").html(''); // clear any previous plot in window_id
var view = new model.default_view({model: model, el: "#${window_id}"});
} else {
load_lib(bokehjs_url, function() {
console.log("Bokeh: BokehJS plotting callback run at", new Date())
var modelid = "${model_id}";
var modeltype = "Plot";
var all_models = ${all_models};
Bokeh.load_models(all_models);
var model = Bokeh.Collections(modeltype).get(modelid);
$("#${window_id}").html(''); // clear any previous plot in window_id
var view = new model.default_view({model: model, el: "#${window_id}"});
}); }]]
local divDefinition = [[<div class="plotdiv" id="${div_id}" style="float:left; width:250px; height:220px; margin-left:0px ; margin-top:0px"></div>]]
for i = 1,#plotsTable do
print(i);
local allmodels = plotsTable[i]:_toAllModels()
local div_id = uuid.new()
local window_id = window_id or div_id
plotsTable[i]._winid = window_id
-- find model_id
local model_id
for k,v in ipairs(allmodels) do
if v.type == 'Plot' then
model_id = v.id
v.attributes.plot_width = 200;
v.attributes.plot_height = 200;
v.attributes.logo = 'None'
v.attributes.toolbar_location = 'None'
v.attributes.title_font_size = '1pt'
v.attributes.min_border = 0;
v.attributes.border_left = 0;
v.attributes.border_right = 0;
v.attributes.border_up = 0;
v.attributes.border_down = 0;
end
end
assert(model_id, "Could not find Plot element in input allmodels");
local html = modelDefinition % {
window_id = window_id,
div_id = div_id,
all_models = encodeAllModels(allmodels),
model_id = model_id
};
local div = divDefinition % {
div_id = div_id
};
gen_models = gen_models .. html
gen_divs = gen_divs .. div
end
local base_template = [[ <script type="text/javascript">
$(function() {
if (typeof (window._bokeh_onload_callbacks) === "undefined"){ window._bokeh_onload_callbacks = []; }
function load_lib(url, callback) { window._bokeh_onload_callbacks.push(callback);
if (window._bokeh_is_loading){ console.log("Bokeh: BokehJS is being loaded, scheduling callback at", new Date()); return null; }
console.log("Bokeh: BokehJS not loaded, scheduling load and callback at", new Date());
window._bokeh_is_loading = true;
var s = document.createElement('script'); s.src = url; s.async = true;
s.onreadystatechange = s.onload = function(){
Bokeh.embed.inject_css("https://cdn.pydata.org/bokeh-0.7.0.min.css");
window._bokeh_onload_callbacks.forEach(function(callback){callback()});
};
s.onerror = function() { console.warn("failed to load library " + url); };
document.getElementsByTagName("head")[0].appendChild(s);
}
bokehjs_url = "https://cdn.pydata.org/bokeh-0.7.0.min.js"
]] .. gen_models .. [[
});
</script>
]]
local html =
[[ <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.pydata.org/bokeh-0.7.0.min.css" type="text/css" />
<script type="text/javascript" src="https://cdn.pydata.org/bokeh-0.7.0.js"></script> ]]
.. base_template ..
[[ </head>
<body> ]]
.. gen_divs ..
[[ </body>
</html> ]]
return html
end
function plotMultivariateTimeSeries(y)
plot = Plot()
-- Two modes
if torch.type(y) == 'table' then dimSeries = 1; nSeries = #y; else dimSeries = 1; nSeries = y:size(1) end
print(#y);
print(nSeries)
-- Generate index vector
x = torch.linspace(1, y[1]:size(dimSeries), y[1]:size(dimSeries));
for i = 1,nSeries do
curTS = y[i];
plot:line(x, curTS, generateHTMLColor(), 'Series' .. i)
end
plot:legend(true)
plot:title('Line Plot Demo')
plot:draw()
plot:save('fig.html');
os.execute('open fig.html');
end
function plotMultipleTimeSeries(y)
-- Two modes
if torch.type(y) == 'table' then dimSeries = 1; nSeries = #y; else dimSeries = 1; nSeries = y:size(1) end
print(#y);
print(nSeries)
-- Generate index vector
plotTable = {};
for i = 1,nSeries do
local plot = Plot()
curTS = y[i];
x = torch.linspace(1, curTS:size(dimSeries), curTS:size(dimSeries));
plot:line(x, curTS, generateHTMLColor())
plot:title('');
plot:draw()
plotTable[i] = plot;
end
html = multiPlot(plotTable);
local f = assert(io.open('fig.html', 'w'),
'filename cannot be opened in write mode')
f:write(html)
f:close()
os.execute('open fig.html')
end
-- scatter plots
function plotScatter(x, y, groups, groupNames)
plot = Plot();
for i = 1,#groups do
plot:circle(x[groups[i]], y[groups[i]], 'red', groupNames[i]);
end
plot:title('Scatter Plot Demo'):redraw()
plot:xaxis('length'):yaxis('width'):redraw()
plot:legend(true)
plot:redraw()
plot:save('fig.html')
os.execute('open fig.html')
end
----------------------------------------------------------------------
-- Export the weights to image
----------------------------------------------------------------------
function exportWeights(model, baseFile)
linearModules = model:findModules('nn.Linear')
for i = 1, #conv_nodes do
image.save(baseFile .. 'weights_' .. i, linearModules[i].weight);
end
end