-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
executable file
·658 lines (583 loc) · 20.6 KB
/
index.html
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>手写数字识别过程演示</title>
<meta name="description" content="">
<meta name="author" content="felix">
<style>
.layer {
border: 1px solid #999;
margin-bottom: 5px;
text-align: left;
padding: 10px;
}
.layer_act {
width: 450px;
float: right;
}
.ltconv {
background-color: #FDD;
}
.ltrelu {
background-color: #FDF;
}
.ltpool {
background-color: #DDF;
}
.ltsoftmax {
background-color: #FFD;
}
.ltfc {
background-color: #DFF;
}
.ltlrn {
background-color: #DFD;
}
.ltdropout {
background-color: #AAA;
}
.ltitle {
color: #333;
font-size: 18px;
}
.actmap {
margin: 1px;
}
#trainstats {
text-align: left;
}
.clear {
clear: both;
}
#wrap {
width: 800px;
margin-left: auto;
margin-right: auto;
}
h1 {
font-size: 16px;
color: #333;
background-color: #DDD;
border-bottom: 1px #999 solid;
text-align: center;
}
.secpart {
width: 400px;
float: left;
}
#lossgraph {
/*border: 1px solid #F0F;*/
width: 100%;
}
.probsdiv canvas {
float: left;
}
.probsdiv {
height: 60px;
width: 180px;
display: inline-block;
font-size: 12px;
box-shadow: 0px 0px 2px 2px #EEE;
margin: 5px;
padding: 5px;
color: black;
}
.pp {
margin: 1px;
padding: 1px;
}
#testset_acc {
margin-bottom: 200px;
}
body {
font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
}
</style>
<script src="./index_files/jquery-1.8.3.min.js"></script>
<script src="./index_files/vis.js"></script>
<script src="./index_files/util.js"></script>
<script src="./index_files/convnet.js"></script>
<script src="./index_files/mnist_labels.js"></script>
<script>
var layer_defs, net, trainer;
var t = "layer_defs = [];\n\
layer_defs.push({type:'input', out_sx:24, out_sy:24, out_depth:1});\n\
layer_defs.push({type:'conv', sx:5, filters:8, stride:1, pad:2, activation:'relu'});\n\
layer_defs.push({type:'pool', sx:2, stride:2});\n\
layer_defs.push({type:'conv', sx:5, filters:16, stride:1, pad:2, activation:'relu'});\n\
layer_defs.push({type:'pool', sx:3, stride:3});\n\
layer_defs.push({type:'softmax', num_classes:10});\n\
\n\
net = new convnetjs.Net();\n\
net.makeLayers(layer_defs);\n\
\n\
trainer = new convnetjs.SGDTrainer(net, {method:'sgd', batch_size:20, l2_decay:0.001});\n\
";
// 更好的方法是adadelta
// ------------------------
// BEGIN MNIST SPECIFIC STUFF
// ------------------------
classes_txt = ['0','1','2','3','4','5','6','7','8','9'];
var use_validation_data = true;
// 返回{一个图像数据(Vol类型),相应的标签,isval}
var sample_training_instance = function() {
// find an unloaded batch
var bi = Math.floor(Math.random()*loaded_train_batches.length);
var b = loaded_train_batches[bi];
var k = Math.floor(Math.random()*3000); // sample within the batch
var n = b*3000+k;
// load more batches over time
if(step_num%5000===0 && step_num>0) {
for(var i=0;i<num_batches;i++) {
if(!loaded[i]) {
// load it
load_data_batch(i);
break; // okay for now
}
}
}
// fetch the appropriate row of the training image and reshape into a Vol
var p = img_data[b].data;
var x = new convnetjs.Vol(28,28,1,0.0);
var W = 28*28;
for(var i=0;i<W;i++) {
var ix = ((W * k) + i) * 4;
x.w[i] = p[ix]/255.0;
}
x = convnetjs.augment(x, 24);
var isval = use_validation_data && n%10===0 ? true : false;
return {x:x, label:labels[n], isval:isval};
}
// sample a random testing instance
var sample_test_instance = function() {
var b = 20;
var k = Math.floor(Math.random()*3000);
var n = b*3000+k;
var p = img_data[b].data;
var x = new convnetjs.Vol(28,28,1,0.0);
var W = 28*28;
for(var i=0;i<W;i++) {
var ix = ((W * k) + i) * 4;
x.w[i] = p[ix]/255.0;
}
var xs = [];
for(var i=0;i<4;i++) {
xs.push(convnetjs.augment(x, 24));
}
// return multiple augmentations, and we will average the network over them
// to increase performance
return {x:xs, label:labels[n]};
}
// 20 training batches, 1 test。
// 注意跟batch_size不是一个概念,
var num_batches = 21;
var data_img_elts = new Array(num_batches);
var img_data = new Array(num_batches);
var loaded = new Array(num_batches);
var loaded_train_batches = [];
// int main
$(window).load(function() {
$("#newnet").val(t);
eval($("#newnet").val());
update_net_param_display();
for(var k=0;k<loaded.length;k++) { loaded[k] = false; }
load_data_batch(0); // async load train set batch 0 (6 total train batches)
load_data_batch(20); // async load test set (batch 6)
start_fun();
});
var start_fun = function() {
if(loaded[0] && loaded[20]) {
console.log('starting!');
// 在此处设置时间间隔,方便观察网络学习过程中的变化
setInterval(load_and_step, 0); // lets go!
}
else { setTimeout(start_fun, 200); } // keep checking
}
var load_data_batch = function(batch_num) {
// Load the dataset with JS in background
data_img_elts[batch_num] = new Image();
var data_img_elt = data_img_elts[batch_num];
data_img_elt.onload = function() {
var data_canvas = document.createElement('canvas');
data_canvas.width = data_img_elt.width;
data_canvas.height = data_img_elt.height;
var data_ctx = data_canvas.getContext("2d");
data_ctx.drawImage(data_img_elt, 0, 0); // copy it over... bit wasteful :(
//3000(每一个batch的图像数)*4(argb)*28*28(一条手写数字的像素个数)
img_data[batch_num] = data_ctx.getImageData(0, 0, data_canvas.width, data_canvas.height);
loaded[batch_num] = true;
if(batch_num < 20) { loaded_train_batches.push(batch_num); }
console.log('finished loading data batch ' + batch_num);
};
data_img_elt.src = "./mnist/mnist_batch_" + batch_num + ".png";
}
// ------------------------
// END MNIST SPECIFIC STUFF
// ------------------------
var maxmin = cnnutil.maxmin;
var f2t = cnnutil.f2t;
// elt is the element to add all the canvas activation drawings into
// A is the Vol() to use
// scale is a multiplier to make the visualizations larger. Make higher for larger pictures
// if grads is true then gradients are used instead
var draw_activations = function(elt, A, scale, grads) {
var s = scale || 2; // scale
var draw_grads = false;
if(typeof(grads) !== 'undefined') draw_grads = grads;
// get max and min activation to scale the maps automatically
var w = draw_grads ? A.dw : A.w;
var mm = maxmin(w);
// create the canvas elements, draw and add to DOM
for(var d=0;d<A.depth;d++) {
var canv = document.createElement('canvas');
canv.className = 'actmap';
var W = A.sx * s;
var H = A.sy * s;
canv.width = W;
canv.height = H;
var ctx = canv.getContext('2d');
var g = ctx.createImageData(W, H);
for(var x=0;x<A.sx;x++) {
for(var y=0;y<A.sy;y++) {
if(draw_grads) {
var dval = Math.floor((A.get_grad(x,y,d)-mm.minv)/mm.dv*255);
} else {
var dval = Math.floor((A.get(x,y,d)-mm.minv)/mm.dv*255);
}
for(var dx=0;dx<s;dx++) {
for(var dy=0;dy<s;dy++) {
var pp = ((W * (y*s+dy)) + (dx + x*s)) * 4;
for(var i=0;i<3;i++) { g.data[pp + i] = dval; } // rgb
g.data[pp+3] = 255; // alpha channel
}
}
}
}
ctx.putImageData(g, 0, 0);
elt.appendChild(canv);
}
}
// @Letme 可视化的代码
var visualize_activations = function(net, elt) {
// clear the element
elt.innerHTML = "";
// show activations in each layer
var N = net.layers.length;
for(var i=0;i<N;i++) {
var L = net.layers[i];
var layer_div = document.createElement('div');
// visualize activations
var activations_div = document.createElement('div');
activations_div.appendChild(document.createTextNode('Activations:'));
activations_div.appendChild(document.createElement('br'));
activations_div.className = 'layer_act';
var scale = 2;
if(L.layer_type==='softmax' || L.layer_type==='fc') scale = 10; // for softmax
draw_activations(activations_div, L.out_act, scale);
// visualize data gradients
if(L.layer_type !== 'softmax') {
var grad_div = document.createElement('div');
grad_div.appendChild(document.createTextNode('Activation Gradients:'));
grad_div.appendChild(document.createElement('br'));
grad_div.className = 'layer_grad';
var scale = 2;
if(L.layer_type==='softmax' || L.layer_type==='fc') scale = 10; // for softmax
draw_activations(grad_div, L.out_act, scale, true);
activations_div.appendChild(grad_div);
}
// visualize filters if they are of reasonable size
if(L.layer_type === 'conv') {
var filters_div = document.createElement('div');
if(L.filters[0].sx>3) {
// actual weights
filters_div.appendChild(document.createTextNode('Weights:'));
filters_div.appendChild(document.createElement('br'));
for(var j=0;j<L.filters.length;j++) {
filters_div.appendChild(document.createTextNode('('));
draw_activations(filters_div, L.filters[j], 2);
filters_div.appendChild(document.createTextNode(')'));
}
// gradients
filters_div.appendChild(document.createElement('br'));
filters_div.appendChild(document.createTextNode('Weight Gradients:'));
filters_div.appendChild(document.createElement('br'));
for(var j=0;j<L.filters.length;j++) {
filters_div.appendChild(document.createTextNode('('));
draw_activations(filters_div, L.filters[j], 2, true);
filters_div.appendChild(document.createTextNode(')'));
}
} else {
filters_div.appendChild(document.createTextNode('Weights hidden, too small'));
}
activations_div.appendChild(filters_div);
}
layer_div.appendChild(activations_div);
// print some stats on left of the layer
layer_div.className = 'layer ' + 'lt' + L.layer_type;
var title_div = document.createElement('div');
title_div.className = 'ltitle'
var t = L.layer_type + ' (' + L.out_sx + 'x' + L.out_sy + 'x' + L.out_depth + ')';
title_div.appendChild(document.createTextNode(t));
layer_div.appendChild(title_div);
if(L.layer_type==='conv') {
var t = 'filter size ' + L.filters[0].sx + 'x' + L.filters[0].sy + 'x' + L.filters[0].depth + ', stride ' + L.stride;
layer_div.appendChild(document.createTextNode(t));
layer_div.appendChild(document.createElement('br'));
}
if(L.layer_type==='pool') {
var t = 'pooling size ' + L.sx + 'x' + L.sy + ', stride ' + L.stride;
layer_div.appendChild(document.createTextNode(t));
layer_div.appendChild(document.createElement('br'));
}
// find min, max activations and display them
var mma = maxmin(L.out_act.w);
var t = 'max activation: ' + f2t(mma.maxv) + ', min: ' + f2t(mma.minv);
layer_div.appendChild(document.createTextNode(t));
layer_div.appendChild(document.createElement('br'));
var mma = maxmin(L.out_act.dw);
var t = 'max gradient: ' + f2t(mma.maxv) + ', min: ' + f2t(mma.minv);
layer_div.appendChild(document.createTextNode(t));
layer_div.appendChild(document.createElement('br'));
// number of parameters
if(L.layer_type==='conv') {
var tot_params = L.sx*L.sy*L.in_depth*L.filters.length + L.filters.length;
var t = 'parameters: ' + L.filters.length + 'x' + L.sx + 'x' + L.sy + 'x' + L.in_depth + '+' + L.filters.length + ' = ' + tot_params;
layer_div.appendChild(document.createTextNode(t));
layer_div.appendChild(document.createElement('br'));
}
if(L.layer_type==='fc') {
var tot_params = L.num_inputs*L.filters.length + L.filters.length;
var t = 'parameters: ' + L.filters.length + 'x' + L.num_inputs + '+' + L.filters.length + ' = ' + tot_params;
layer_div.appendChild(document.createTextNode(t));
layer_div.appendChild(document.createElement('br'));
}
// css madness needed here...
var clear = document.createElement('div');
clear.className = 'clear';
layer_div.appendChild(clear);
elt.appendChild(layer_div);
}
}
// loads a training image and trains on it with the network
var paused = false;
var load_and_step = function() {
if(paused) return;
var sample = sample_training_instance();
step(sample); // process this image
}
// evaluate current network on test set
var test_predict = function() {
var num_classes = net.layers[net.layers.length-1].out_depth;
document.getElementById('testset_acc').innerHTML = '';
// grab a random test image
for(num=0;num<50;num++) {
var sample = sample_test_instance();
var y = sample.label; // ground truth label
// forward prop it through the network
var aavg = new convnetjs.Vol(1,1,num_classes,0.0);
// ensures we always have a list, regardless if above returns single item or list
var xs = [].concat(sample.x);
var n = xs.length;
for(var i=0;i<n;i++) {
var a = net.forward(xs[i]);
aavg.addFrom(a);
}
var preds = [];
for(var k=0;k<aavg.w.length;k++) { preds.push({k:k,p:aavg.w[k]}); }
preds.sort(function(a,b){return a.p<b.p ? 1:-1;});
var div = document.createElement('div');
div.className = 'testdiv';
// draw the image into a canvas
draw_activations(div, xs[0], 2); // draw Vol into canv
// add predictions
var probsdiv = document.createElement('div');
div.className = 'probsdiv';
var t = '';
for(var k=0;k<3;k++) {
var col = preds[k].k===y ? 'rgb(85,187,85)' : 'rgb(187,85,85)';
t += '<div class=\"pp\" style=\"width:' + Math.floor(preds[k].p/n*100) + 'px; margin-left: 60px; background-color:' + col + ';\">' + classes_txt[preds[k].k] + '</div>'
}
probsdiv.innerHTML = t;
div.appendChild(probsdiv);
// add it into DOM
$("#testset_acc").append(div).fadeIn(1000);
}
}
var lossGraph = new cnnvis.Graph();
var xLossWindow = new cnnutil.Window(100);
var wLossWindow = new cnnutil.Window(100);
var trainAccWindow = new cnnutil.Window(100);
var valAccWindow = new cnnutil.Window(100);
var step_num = 0;
var step = function(sample) {
var x = sample.x;
var y = sample.label;
if(sample.isval) {
// use x to build our estimate of validation error
net.forward(x);
var yhat = net.getPrediction();
var val_acc = yhat === y ? 1.0 : 0.0;
valAccWindow.add(val_acc);
return; // get out
}
// train on it with network
var stats = trainer.train(x, y);
var lossx = stats.cost_loss;
var lossw = stats.l2_decay_loss;
// keep track of stats such as the average training error and loss
var yhat = net.getPrediction();
var train_acc = yhat === y ? 1.0 : 0.0;
xLossWindow.add(lossx);
wLossWindow.add(lossw);
trainAccWindow.add(train_acc);
// visualize training status
var train_elt = document.getElementById("trainstats");
train_elt.innerHTML = '';
var t = '每个样本前馈所花时间: ' + stats.fwd_time + 'ms';
train_elt.appendChild(document.createTextNode(t));
train_elt.appendChild(document.createElement('br'));
var t = '每个样本反馈所花时间: ' + stats.bwd_time + 'ms';
train_elt.appendChild(document.createTextNode(t));
train_elt.appendChild(document.createElement('br'));
var t = 'loss值: ' + (f2t(xLossWindow.get_average()+wLossWindow.get_average()));
train_elt.appendChild(document.createTextNode(t));
train_elt.appendChild(document.createElement('br'));
var t = '准确率: ' + f2t(trainAccWindow.get_average());
train_elt.appendChild(document.createTextNode(t));
train_elt.appendChild(document.createElement('br'));
var t = '已经训练的样本数: ' + step_num;
train_elt.appendChild(document.createTextNode(t));
train_elt.appendChild(document.createElement('br'));
// visualize activations
if(step_num % 100 === 0) {
var vis_elt = document.getElementById("visnet");
visualize_activations(net, vis_elt);
}
// log progress to graph, (full loss)
if(step_num % 200 === 0) {
var xa = xLossWindow.get_average();
var xw = wLossWindow.get_average();
if(xa >= 0 && xw >= 0) { // if they are -1 it means not enough data was accumulated yet for estimates
lossGraph.add(step_num, xa + xw);
lossGraph.drawSelf(document.getElementById("lossgraph"));
}
}
// run prediction on test set
if(step_num % 1000 === 0) {
test_predict();
}
step_num++;
}
// user settings
var change_lr = function() {
trainer.learning_rate = parseFloat(document.getElementById("lr_input").value);
update_net_param_display();
}
var change_momentum = function() {
trainer.momentum = parseFloat(document.getElementById("momentum_input").value);
update_net_param_display();
}
var change_batch_size = function() {
trainer.batch_size = parseFloat(document.getElementById("batch_size_input").value);
update_net_param_display();
}
var change_decay = function() {
trainer.l2_decay = parseFloat(document.getElementById("decay_input").value);
update_net_param_display();
}
var update_net_param_display = function() {
document.getElementById('lr_input').value = trainer.learning_rate;
document.getElementById('momentum_input').value = trainer.momentum;
document.getElementById('batch_size_input').value = trainer.batch_size;
document.getElementById('decay_input').value = trainer.l2_decay;
}
var toggle_pause = function() {
paused = !paused;
var btn = document.getElementById('buttontp');
if(paused) { btn.value = '开始' }
else { btn.value = '暂停'; }
}
var dump_json = function() {
document.getElementById("dumpjson").value = JSON.stringify(net.toJSON());
}
var clear_graph = function() {
lossGraph = new cnnvis.Graph(); // reinit graph too
}
var reset_all = function() {
update_net_param_display();
// reinit windows that keep track of val/train accuracies
xLossWindow.reset();
wLossWindow.reset();
trainAccWindow.reset();
valAccWindow.reset();
lossGraph = new cnnvis.Graph(); // reinit graph too
step_num = 0;
}
var load_from_json = function() {
var jsonString = document.getElementById("dumpjson").value;
var json = JSON.parse(jsonString);
net = new convnetjs.Net();
net.fromJSON(json);
reset_all();
}
var change_net = function() {
eval($("#newnet").val());
reset_all();
}
</script>
<body>
<div id="wrap">
<h2 style="text-align: center;">手写数字识别过程演示</h2>
<h1>描述</h1>
<p>
本程序每次处理一个28*28大小的MNIST图片,修剪为24*24大小后作为神经网络的输入层。训练数据集大小为60000条,测试数据为3000条。经过指定批处理次的训练过程后,更新一次权重;经过100次训练后,将网络当前的状态可视化显示;经过1000次训练过程后,从3000条测试数据中随机选出50条进行预测,并判断正误。
</p>
<h1>训练状态</h1>
<div class="divsec" style="270px;">
<div class="secpart">
<input id="buttontp" type="submit" value="暂停" onclick="toggle_pause();" style="width: 100px; height:30px; background-color: #FCC;"/>
<div id="trainstats"></div>
<div id="controls">
学习速率: <input name="lri" type="text" maxlength="20" id="lr_input"/>
<input id="buttonlr" type="submit" value="调整" onclick="change_lr();"/>
<br />
动量参数: <input name="momi" type="text" maxlength="20" id="momentum_input"/>
<input id="buttonmom" type="submit" value="调整" onclick="change_momentum();"/>
<br />
批处理大小: <input name="bsi" type="text" maxlength="20" id="batch_size_input"/>
<input id="buttonbs" type="submit" value="调整" onclick="change_batch_size();"/>
<br />
权重衰减率: <input name="wdi" type="text" maxlength="20" id="decay_input"/>
<input id="buttonwd" type="submit" value="调整" onclick="change_decay();"/>
</div>
<input id="buttondj" type="submit" value="以JSON格式保存网络快照" onclick="dump_json();"/><br />
<input id="buttonlfj" type="submit" value="使用快照初始化网络" onclick="load_from_json();"/><br />
<textarea id="dumpjson"></textarea>
</div>
<div class="secpart">
<div>
Loss:<br />
<canvas id="lossgraph">
</canvas>
<br />
<input id="buttoncg" type="submit" value="清空图表" onclick="clear_graph();"/>
</div>
</div>
<div style="clear:both;"></div>
</div>
<h1>配置网络结构及训练模型</h1>
<div>
<textarea id="newnet" style="width:100%; height:200px;"></textarea><br />
<input id="buttonnn" type="submit" value="调整网络结构" onclick="change_net();" style="width:200px;height:30px;"/>
</div>
<div class="divsec">
<h1>网络可视化</h1>
<div id="visnet"></div>
</div>
<div class="divsec">
<h1>在测试集上的预测结果</h1>
<div id="testset_acc"></div>
</div>
</div>
</body>
</html>