-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvisualai.html
1263 lines (1061 loc) · 33.4 KB
/
visualai.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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!-- Jonathon Rice, Richard DiBacco, Soliman Alnaizy -->
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>Neural Network Builder</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<script src="https://threejs.org/build/three.js"></script>
<script src='https://threejs.org/examples/js/libs/dat.gui.min.js'></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.14.1/dist/tf.min.js"></script>
<script src="lib/main.js"></script>
<script type= "module" src="lib/model.js"></script>
<script src="lib/Layer.js"></script>
<script src="lib/Network.js"></script>
<script type="text/javascript" src="lib/colormap.json"></script>
<script src="lib/textRender.js"></script>
<script type= "module">
// GLOBAL VARIABLES
var container; // Will be used to add the .js script to the browser
var camera, raycaster, renderer, scene; // Three.js essentials
var controls; // For orbital controls
var mouse = new THREE.Vector3(); // For the raycaster
var selectedObject = null, group; // For the raycaster
var theta = 0; // Camera rotating during animation
var linesInScene = []; // Holds currently rendered lines
var cubeArray = []; // Holds currently rendered cubes
var numbox = 0; // count total cubes
var layerSize = []; // independent size of each layer
var layerSum = []; // total nodes up to current layer
var allColors = []; // holds all current colors
var cubeToAnimate = 784; // Where input ends and network begins
var waitOver = false; // when 1st colors are ready
var IMG; // holds current input img
var imgNum = 5; // image number from dataset
var useMap = 1; // color space being used
var gui; // dat gui
var highlight = new THREE.Color ( 1,0,0 ); // Object highlight for raycaster
var network = []; // for layer and channel control: [layer][channel][neuron]
var opacity = false;
var aniCount = 0;
var lines = [];
// Button stuff
var isCurrent = false, plzRestart = false, isPlaying = false, isTraining = false;
// CONSTANTS
const RADIUS = 750; // Camera rotation and movement
const PANSPEED = 5, ROTATIONSPEED = 1;
const PANDISTANCE = 0; // Determines how far the camera pans
const IMAGE_SIZE = 784;
// Grabs model data from other js module
import {data, model, train, done, createModel, layers} from './lib/model.js';
let colorSelect = {
map : "Viridis"
};
let trainSelect = {
switch : "On"
};
// drop down to select color space
let colorChange = function() {
switch (colorSelect.map) {
case "Viridis": useMap = 1; break;
case "Plasma": useMap = 2; break;
case "Jet": useMap = 3; break;
}
let RGB = colorMap(1, useMap);
highlight = new THREE.Color( RGB[0], RGB[1], RGB[2] );
imgNum--;
next();
}
let animateTraining = function() {
switch (trainSelect.switch) {
case "On": isTraining = true; break;
case "Off": isTraining = false; break;
}
}
let alterModel = {
clearModel: function() {
let alayers = [];
alayers.push(tf.layers.flatten({inputShape: [28, 28, 1]}));
alayers.push(tf.layers.dense({
units: 10,
kernelInitializer: 'varianceScaling',
activation: 'softmax'
}));
createModel(alayers);
calcLayerSizes();
renderModel();
console.log(layerSize);
console.log(layerSum);
console.log(network);
colorCoat();
},
kernel: 7,
filters: 4,
addConv: function() {
let layers2 = [];
let index = 0;
for (let i = 0; i < layers.length; i++)
{
if (layers[i].name.includes("flatten"))
{
index = i;
break;
}
else
layers2.push(replaceLayer(layers[i]));
}
if (index != 0 && layers[index-1].inboundNodes[0].outputShapes[0][1] < this.kernel)
return;
if (index == 0)
{
layers2.push(tf.layers.conv2d({
inputShape: [28, 28, 1],
kernelSize: this.kernel,
filters: this.filters,
strides: 1,
activation: 'relu',
kernelInitializer: 'varianceScaling'
}));
}
else
layers2.push(tf.layers.conv2d({
kernelSize: this.kernel,
filters: this.filters,
strides: 1,
activation: 'relu',
kernelInitializer: 'varianceScaling'
}));
for (let i = index; i < layers.length; i++)
layers2.push(replaceLayer(layers[i]));
createModel(layers2);
calcLayerSizes();
renderModel();
console.log(layerSize);
console.log(layerSum);
console.log(network);
colorCoat();
},
addPool: function() {
let layers2 = [];
let index = 0;
for (let i = 0; i < layers.length; i++)
{
if (layers[i].name.includes("flatten"))
{
index = i;
break;
}
else
layers2.push(replaceLayer(layers[i]));
}
if (index != 0 && layers[index-1].inboundNodes[0].outputShapes[0][1] < 4)
return;
if (index == 0)
{
layers2.push(tf.layers.maxPooling2d({
inputShape: [28, 28, 1],
poolSize: [2,2],
strides: [2,2]
}));
}
else
layers2.push(tf.layers.maxPooling2d({
poolSize: [2,2],
strides: [2,2]
}));
for (let i = index; i < layers.length; i++)
layers2.push(replaceLayer(layers[i]));
createModel(layers2);
calcLayerSizes();
renderModel();
console.log(layerSize);
console.log(layerSum);
console.log(network);
colorCoat();
},
neurons: 50,
addDense: function() {
let layers2 = [];
let index = 0;
for (let i = 0; i < layers.length-1; i++)
layers2.push(replaceLayer(layers[i]));
layers2.push(tf.layers.dense({
units: this.neurons,
kernelInitializer: 'varianceScaling',
activation: 'relu'
}));
layers2.push(tf.layers.dense({
units: 10,
kernelInitializer: 'varianceScaling',
activation: 'softmax'
}));
createModel(layers2);
calcLayerSizes();
renderModel();
console.log(layerSize);
console.log(layerSum);
console.log(network);
colorCoat();
}
};
function replaceLayer( layer ) {
if (layer.outboundNodes.length == 0)
return tf.layers.dense({
units: 10,
kernelInitializer: 'varianceScaling',
activation: 'softmax'
});
if (layer.name.includes("flatten"))
{
if (layer.batchInputShape != null)
return tf.layers.flatten({inputShape: [28, 28, 1]});
else
return tf.layers.flatten();
}
if (layer.name.includes("conv"))
{
if (layer.batchInputShape != null)
return tf.layers.conv2d({
inputShape: [28, 28, 1],
kernelSize: layer.kernelSize[0],
filters: layer.filters,
strides: 1,
activation: 'relu',
kernelInitializer: 'varianceScaling'
});
else
return tf.layers.conv2d({
kernelSize: layer.kernelSize[0],
filters: layer.filters,
strides: 1,
activation: 'relu',
kernelInitializer: 'varianceScaling'
});
}
if (layer.name.includes("pool"))
{
if (layer.batchInputShape != null)
return tf.layers.maxPooling2d({
inputShape: [28, 28, 1],
poolSize: [2,2],
strides: [2,2]
});
else
return tf.layers.maxPooling2d({
poolSize: [2,2],
strides: [2,2]
});
}
if (layer.name.includes("dense"))
return tf.layers.dense({
units: layer.units,
kernelInitializer: 'varianceScaling',
activation: 'relu'
});
}
// The first function that loads
window.onload = function() {
init();
animate();
}
// normalizes output of an entire layer
function normalize(array) {
let maxi = Math.max.apply(Math, array);
let mini = Math.min.apply(Math, array);
let ratio = maxi - mini;
let i, j, k;
for (i = 0; i < array.length; i++) {
array[i] += Math.abs(mini);
array[i] /= ratio;
}
return array;
}
// Colormap functions, if no color space passed then gray scale used
function colorMap(value, map = 0) {
let RGB = [];
if (value > 1)
{
value = 1;
}
// gray scale
if (map == 0)
{
RGB.push(value);
RGB.push(value);
RGB.push(value);
}
if (map == 1)
{
RGB.push(viridis[Math.round(255*value)][0]);
RGB.push(viridis[Math.round(255*value)][1]);
RGB.push(viridis[Math.round(255*value)][2]);
}
if (map == 2)
{
RGB.push(plasma[Math.round(255*value)][0]);
RGB.push(plasma[Math.round(255*value)][1]);
RGB.push(plasma[Math.round(255*value)][2]);
}
// jet, blue to green to red heatmap
if (map == 3)
{
if(value <= .5)
{
RGB.push(0);
RGB.push(2*value);
RGB.push(1 - 2*value);
}
else
{
RGB.push(2*value - 1);
RGB.push(2 - 2*value);
RGB.push(0);
}
}
return RGB;
}
// Draws a line that connects the point p1 to point p2
function draw( p1, p2 ) {
let mat = new THREE.LineBasicMaterial( { color: highlight, linewidth: 2 } );
let geo = new THREE.Geometry();
geo.vertices.push( p1 );
geo.vertices.push( p2 );
let line = new THREE.Line( geo, mat );
scene.add( line );
return line;
}
function drawLine( from, to, color = highlight) {
let mat = new THREE.LineBasicMaterial( { color: color, linewidth: 2 } );
let geo = new THREE.Geometry();
geo.vertices.push( from );
geo.vertices.push( to );
let line = new THREE.Line( geo, mat );
linesInScene.push(line);
scene.add( line );
return line;
}
// output to color
function findRGB( layer, dense, num )
{
let RGB = [], RGB2 = [];
let weights;
// console.log(layer);
if (!ilayer && !model.getLayer('', num).name.includes("pool"))
{
weights = model.layers[num].getWeights()[0].dataSync();
weights = normalize(weights.slice(0));
}
if(!dense)
{
for(let v = 0; v < layer[0][0][0].length; v++)
{
for(let i = -layer[0][0].length/2; i < layer[0][0].length/2; i++)
{
for(let j = -layer[0].length/2; j < layer[0].length/2; j++)
{
if(ilayer)
{
RGB = colorMap(layer[0][j+layer[0].length/2][i+layer[0][0].length/2][v]);
}
else
{
RGB = colorMap(layer[0][j+layer[0].length/2][i+layer[0][0].length/2][v], useMap);
}
let color = new THREE.Color( RGB[0], RGB[1], RGB[2] );
allColors.push(color);
if (!ilayer && !model.getLayer('', num).name.includes("pool"))
{
allColors[allColors.length-1].lineColors = [];
let vol = model.layers[num].getWeights()[0].shape;
for (let z = 0; z < vol[2]; z ++)
for (let n = 0; n < vol[1]; n++)
for (let k = 0; k < vol[0]; k++)
{
RGB2 = colorMap(weights[k+vol[0]*n+vol[0]*vol[1]*z+vol[0]*vol[1]*vol[2]*v], useMap);
color = new THREE.Color( RGB2[0], RGB2[1], RGB2[2] );
allColors[allColors.length-1].lineColors.push(color);
}
}
}
}
}
}
if(dense)
{
for(let i = 0; i < layer.length; i++)
{
RGB = colorMap(layer[i], useMap);
let color = new THREE.Color( RGB[0], RGB[1], RGB[2] );
allColors.push(color);
if (!ilayer && !model.getLayer('', num).name.includes("pool"))
{
allColors[allColors.length-1].lineColors = [];
let vol = model.layers[num].getWeights()[0].shape;
for (let k = 0; k < vol[0]; k++)
{
RGB2 = colorMap(weights[k+vol[0]*i], useMap);
color = new THREE.Color( RGB2[0], RGB2[1], RGB2[2] );
allColors[allColors.length-1].lineColors.push(color);
}
}
}
}
}
// 1D array, channels, width, height
// outputs js array in original shape
function oneDToMany( layer, n, m , l ) {
let arr = Array.prototype.slice.call(layer);
let newArr = [];
let newArr2 = [];
let finalarr = [];
while(arr.length)
{
newArr.push(arr.splice(0,n));
}
while(newArr.length)
{
newArr2.push(newArr.splice(0,m));
}
while(newArr2.length)
{
finalarr.push(newArr2.splice(0,l));
}
return finalarr;
}
// layer rendering abstraction for imgs and conv layers
var ilayer = true;
function imgVis(layer, scene, group, num)
{
let RGB = [];
let stuffz;
let geometry = new THREE.BoxGeometry(10, 10, 10);
if (num >= 0)
{
network.push([]);
if (!model.getLayer('', num).name.includes("pool"))
network[network.length-1].wShape = model.layers[num].getWeights()[0].shape;
network[network.length-1].iShape = model.layers[num].inboundNodes[0].inputShapes[0];
network[network.length-1].oShape = model.layers[num].inboundNodes[0].outputShapes[0];
network[network.length-1].view = false;
}
for(let v = 0; v < layer[0][0][0].length; v++)
{
if (num >= 0)
network[network.length-1].push([]);
for(let i = -layer[0][0].length/2; i < layer[0][0].length/2; i++)
{
for(let j = -layer[0].length/2; j < layer[0].length/2; j++)
{
if(ilayer)
{
RGB = colorMap(layer[0][j+layer[0].length/2][i+layer[0][0].length/2][v]);
}
else
{
RGB = colorMap(layer[0][j+layer[0].length/2][i+layer[0][0].length/2][v], useMap);
}
let colors = new THREE.Color( RGB[0], RGB[1], RGB[2] );
let material = new THREE.MeshLambertMaterial( { color: colors } );
let cube = new THREE.Mesh( geometry, material );
cube.position.x += 12*i;
cube.position.y += 12*(-j);
if(network.length == 1)
{
cube.position.z += v*-30 + (-200+cubeArray[783].position.z);
}
else if (network.length > 1)
{
cube.position.z += v*-30 + (-200 + network[network.length-2][network[network.length-2].length-1][0].position.z);
}
cube.original = colors;
cube.number = numbox++;
cube.layer = network.length-1;
cube.channel = v;
cube.material.transparent = true;
cube.material.opacity = 1.0;
cubeArray.push( cube );
scene.add( cube );
group.add( cube );
if (num >= 0)
network[network.length-1][v].push(cube);
}
}
}
if (!ilayer)
{
stuffz = renderText(scene, group, network[network.length-1][0][0].position, model.getLayer('', num).name);
scene = stuffz.scene;
group = stuffz.group;
}
return {scene: scene, group: group};
}
// Render fully connected layers
var dense1 = true;
function denseVis(layer, scene, group, num)
{
let RGB = [];
let stuffz;
let geometry = new THREE.BoxGeometry(10, 10, 10);
if (num >= 0)
{
network.push([]);
network[network.length-1].wShape = model.layers[num].getWeights()[0].shape;
network[network.length-1].iShape = model.layers[num].inboundNodes[0].inputShapes[0];
network[network.length-1].oShape = model.layers[num].inboundNodes[0].outputShapes[0];
network[network.length-1].view = false;
network[network.length-1].push([]);
}
for(let j = -layer.length/2; j < layer.length/2; j++)
{
RGB = colorMap(layer[j+layer.length/2], useMap);
let colors = new THREE.Color( RGB[0], RGB[1], RGB[2] );
let material = new THREE.MeshLambertMaterial( { color: colors } );
let cube = new THREE.Mesh( geometry, material );
cube.position.x += 12*j;
if(network.length == 1)
{
cube.position.z += (-150+cubeArray[783].position.z);
}
else if (network.length > 1)
{
cube.position.z += (-150 + network[network.length-2][network[network.length-2].length-1][0].position.z);
}
cube.original = colors;
cube.number = numbox++;
cube.layer = network.length-1;
cube.channel = 0;
cube.material.opacity = 1.0;
//console.log(cube.number);
cubeArray.push( cube );
// getLinesForCube( cube );
scene.add( cube );
group.add( cube );
network[network.length-1][0].push(cube);
}
if (model.layers[num].outboundNodes.length != 0)
stuffz = renderText(scene, group, network[network.length-1][0][0].position, model.getLayer('', num).name);
else
stuffz = renderText(scene, group, network[network.length-1][0][0].position, "output");
scene = stuffz.scene;
group = stuffz.group;
return {scene: scene, group: group};
}
// Computes new outputs for network and converts to color
function colorCoat()
{
allColors = [];
// input layer
ilayer = true;
findRGB(IMG, false, -1);
ilayer = false;
let netout = tf.tensor4d(IMG);
for (let i = 0; i < model.layers.length; i++)
{
let currOut, tensorOut;
netout = model.getLayer('', i).apply(netout);
if(!model.getLayer('', i).name.includes("flatten"))
{
// if not output layer, normalize
if (model.layers[i].outboundNodes.length != 0)
currOut = normalize(netout.dataSync().slice(0));
else
currOut = netout.dataSync();
if(!model.getLayer('', i).name.includes("dense"))
{
tensorOut = oneDToMany(currOut, netout.shape[3], netout.shape[2], netout.shape[1]);
findRGB(tensorOut, false, i);
}
else
findRGB(currOut, true, i);
}
currOut = null;
tensorOut = null;
}
netout = null;
}
// calculates size of each layer
function calcLayerSizes()
{
layerSize = [];
layerSum = [];
let ntotal = IMAGE_SIZE;
layerSize.push(IMAGE_SIZE);
layerSum.push(ntotal);
for (let i = 0; i < model.layers.length; i++)
{
// dont include flatten layers
if (!model.getLayer('', i).name.includes("flatten"))
{
// console.log(model.layers[i]);
let outputShape = model.layers[i].inboundNodes[0].outputShapes[0];
let totalSize = 1;
for (let j = 1; j < outputShape.length; j++)
{
totalSize *= outputShape[j];
}
layerSize.push(totalSize);
ntotal += totalSize
layerSum.push(ntotal);
}
}
}
function renderModel()
{
// scene.remove(group);
while (group.children.length)
{
group.children[0].material.dispose();
group.children[0].geometry.dispose();
scene.remove(group.children[0]);
group.remove(group.children[0]);
}
group = null;
group = new THREE.Group();
scene.add(group);
network = [];
cubeArray = [];
numbox = 0;
ilayer = true;
var input = data.datasetImages.slice(IMAGE_SIZE*imgNum, IMAGE_SIZE*(imgNum+1));
IMG = oneDToMany(input, 1, 28, 28);
var stuffz = imgVis(IMG, scene, group, -1);
scene = stuffz.scene;
group = stuffz.group;
ilayer = false;
// loop through all layers, abstraction
var stuffz, outputArray;
var output = tf.tensor4d(IMG);
for(let i = 0; i < model.layers.length; i++)
{
// layer computation
output = model.getLayer('', i).apply(output);
// Visualize all layers besides flatten
if (!model.getLayer('', i).name.includes("flatten"))
{
// normalize layer data for color space
outputArray = normalize(output.dataSync().slice(0));
// conv or pool layers
if (!model.getLayer('', i).name.includes("dense"))
{
var fmap = oneDToMany(outputArray, output.shape[3], output.shape[2], output.shape[1]);
stuffz = imgVis(fmap, scene, group, i);
}
// dense layers
else
{
// not output layer
if (i != model.layers.length - 1)
stuffz = denseVis(outputArray, scene, group, i);
// output layer, softmax so no normalization
else
{
dense1 = false;
stuffz = denseVis(output.dataSync(), scene, group, i);
}
}
scene = stuffz.scene;
group = stuffz.group;
}
}
}
// Initializes all the necessary variables for a basic THREE.js application
async function init()
{
container = document.createElement( 'div' );
document.body.appendChild( container );
// Renderer stuff
renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setPixelRatio( window.devicePixelRatio );
container.appendChild( renderer.domElement );
// Setting the scene
scene = new THREE.Scene();
// Camera stuff
var aspect = window.innerWidth / window.innerHeight;
camera = new THREE.PerspectiveCamera( 45, aspect, 1, 5000 );
camera.position.set( 0, 0, RADIUS );
camera.lookAt( scene.position );
scene.add( camera );
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.enableDamping = true;
controls.dampingFactor = 0.25;
// Light stuff
var ambientLight = new THREE.AmbientLight( 0xFFFFFF, 0.5 );
scene.add( ambientLight );
var dirLight = new THREE.DirectionalLight( 0xffffff, 0.9 );
// dirLight.position.set( 1, 0, 1 ).normalize();
dirLight.position.copy( camera.position );
scene.add( dirLight );
controls.addEventListener( 'change', light_update );
function light_update()
{
dirLight.position.copy( camera.position );
}
// A Raycaster can tell what object is the mouse hovering over
raycaster = new THREE.Raycaster();
group = new THREE.Group();
scene.add( group );
calcLayerSizes();
renderModel();
console.log(layerSize);
console.log(layerSum);
console.log(network);
colorCoat();
waitOver = true;
// Makes the animation adapt to the size of the window
window.addEventListener( "resize", resize, false );
// This is what highlights the cubes when the mouse is over an object
window.addEventListener( "mousemove", highlightObject, false );
window.addEventListener( "touchmove", highlightObject, false );
// Turn off frozen opacity, give separate function?
window.addEventListener( "click", function(){if(opacity) opacity = false;} );
// Turn off frozen opacity
window.addEventListener( "click", function(){if(opacity) opacity = false;} );
gui = new dat.GUI();
gui.add(colorSelect, "map",
["Viridis","Plasma","Jet"] )
.name( "Color Map" )
.onChange( colorChange );
gui.add(trainSelect, "switch",
["On","Off"] )
.name( "Animate Training" )
.onChange( animateTraining );
var f1 = gui.addFolder('Add Conv Layer');
f1.add(alterModel, "kernel").step(1);
f1.add(alterModel, "filters").step(1);
f1.add(alterModel, "addConv");
var f2 = gui.addFolder('Add Pool Layer');
f2.add(alterModel, "addPool");
var f3 = gui.addFolder('Add Dense Layer');
f3.add(alterModel, 'neurons').step(1);
f3.add(alterModel, "addDense");
gui.add(alterModel, "clearModel");
}
// The program adapts to the size of the browser window
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function getLinesForCube(cube)
{
let index = whichLayer(cube.number);
// console.log(cube.number);
cube.lines = [];
let i,j,k;
let start = layerSum[index]-layerSize[index];
let dim = network[index].oShape[1];
let idim = network[index].iShape[1];
let area = dim*dim;
// pooling
if (network[index].wShape == null)
{
for (i = 0; i <= 1; i++)
{
for (j = 0; j <= 1; j++)
{
var col = Math.floor((( cube.number - layerSum[index] ) % area ) / dim);
var row = (( cube.number - layerSum[index] ) % area ) % dim;
lines.push( {from: cubeArray[ cube.number ],
to: cubeArray[start + (idim*idim*cube.channel) + idim * col*2 + i + idim * j + row*2] } );
}
}
return;
}
// conv layer
if (network[index].wShape.length == 4)
{
// start += idim*2 + 2;
for (k = 0; k < network[index].wShape[2]; k++)
{
for (i = 0; i < network[index].wShape[1]; i++)
{
for (j = 0; j < network[index].wShape[1]; j++)
{
var col = Math.floor((( cube.number - layerSum[index] ) % area ) / dim);
var row = (( cube.number - layerSum[index] ) % area ) % dim;
lines.push( { from: cubeArray[ cube.number ],
to: cubeArray[ col * idim + (start + idim*idim*k) + row + i + idim*j] } );
}
}
}
return;
}
// dense layer
if (network[index].wShape.length == 2)
{
for (j = start; j < layerSum[index]; j++)
{
lines.push( {from: cubeArray[ cube.number ],
to: cubeArray[ j ] } );
}
return;
}
}
// ignores flatten and reshape layers
function whichLayer(num)
{
let index = -1;
for (let i = 0; i < layerSum.length-1; i++)
{
if(num >= layerSum[i] && num < layerSum[i+1])
{
index = i;
break;
}
}
return index;
}
// function construct() {
// }
// For the raycaster
function highlightObject( event )
{
// event.preventDefault();
// Restore the cube back to it's original once the mouse is no longer over it
if ( selectedObject ) {
if (waitOver)
selectedObject.material.color = allColors[selectedObject.number];
else
selectedObject.material.color = selectedObject.original;
// set back to non transparent
if(selectedObject.number > 783 && network[selectedObject.layer].view == false)
for (let v = 0; v < network[selectedObject.layer].length; v++)
{
if (v != selectedObject.channel)
{
for (let i = 0; i < network[selectedObject.layer][v].length; i++)
network[selectedObject.layer][v][i].visible = true;
}
}
selectedObject = null;
for (let i = 0; i < linesInScene.length; i++)
scene.remove( linesInScene[i] );
linesInScene = [];
lines = [];
}
var intersects = getIntersects( event.layerX, event.layerY );
// If the mouse is intersecting with an object, change it's color
if ( intersects.length > 0 )
{
var res = intersects.filter( function ( res )
{