-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexplain.js
More file actions
1565 lines (1283 loc) · 43.7 KB
/
explain.js
File metadata and controls
1565 lines (1283 loc) · 43.7 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
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
"use strict";
function visualizeNumbersOnCanvas(numberArray, blockWidth = 1, blockHeight = 25) {
assert(Array.isArray(numberArray), "visualizeNumbersOnCanvas: numberArray is not an Array, but " + typeof(numberArray));
assert(typeof(blockWidth) == "number", "blockWidth is not a number, but " + typeof(blockWidth));
assert(typeof(blockHeight) == "number", "blockHeight is not a number, but " + typeof(blockHeight));
// Create or retrieve the canvas element
var canvas = document.createElement("canvas");
canvas.id = "neurons_canvas_" + uuidv4();
canvas.classList.add("neurons_canvas_class");
// Calculate the canvas width based on the number of elements
var canvasWidth = numberArray.length * blockWidth;
var canvasHeight = blockHeight;
// Set the canvas dimensions
canvas.width = canvasWidth;
canvas.height = canvasHeight;
var ctx = canvas.getContext("2d");
var blocksPerRow = Math.floor(canvas.width / blockWidth);
for (var numberArray_idx = 0; numberArray_idx < numberArray.length; numberArray_idx++) {
var value = numberArray[numberArray_idx];
var grayscaleValue = Math.round((value / numberArray[numberArray.length - 1]) * 255);
var color = "rgb(" + grayscaleValue + "," + grayscaleValue + "," + grayscaleValue + ")";
var x = (numberArray_idx % blocksPerRow) * blockWidth;
var y = Math.floor(numberArray_idx / blocksPerRow) * blockHeight;
ctx.fillStyle = color;
ctx.fillRect(x, y, blockWidth, blockHeight);
}
return canvas;
}
function normalize_to_rgb_min_max (x, min, max) {
assert(typeof(x) == "number", "x is not a number");
if(typeof(max) != "number" || typeof(min) != "number") {
return x;
}
assert(typeof(x) == "number", "x is not a number, but " + typeof(x));
assert(typeof(min) == "number", "min is not a number, but " + typeof(min));
assert(typeof(max) == "number", "max is not a number, but " + typeof(max));
assert(!isNaN(x), "x is NaN");
assert(!isNaN(min), "min is NaN");
assert(!isNaN(max), "max is NaN");
var multiplicator = x - min;
var divisor = max - min;
//log("x:", x, "min:", min, "multiplicator:", multiplicator, "divisor:", divisor);
if(divisor == 0) {
return 0;
}
assert(typeof(multiplicator) == "number", "multiplicator is not a number, but " + typeof(multiplicator));
assert(typeof(divisor) == "number", "divisor is not a number, but " + typeof(divisor));
assert(!isNaN(divisor), "divisor is NaN");
assert(!isNaN(multiplicator), "multiplicator is NaN");
var to_be_parsed_as_int = 255 * multiplicator / divisor;
var val = parse_int(to_be_parsed_as_int);
if(val > 255) {
val = 255;
} else if (val < 0) {
val = 0;
}
return val;
}
function get_canvas_in_class (layer, classname, dont_append, use_uuid=0) {
var _uuid = "";
var _uuid_str = "";
if (use_uuid) {
_uuid = uuidv4();
_uuid_str = " class='generated_canvas' id='" + _uuid + "'";
}
var new_canvas = $("<canvas" + _uuid_str + "/>", {class: "layer_image"}).prop({
width: 0,
height: 0
});
if(!dont_append) {
$($("." + classname)[layer]).append(new_canvas);
}
return new_canvas[0];
}
function get_dim(a) {
if(!a) {
return 0;
}
var dim = [];
for (;;) {
dim.push(a.length);
if (Array.isArray(a[0])) {
a = a[0];
} else {
break;
}
}
return dim;
}
function shape_looks_like_image_data (shape) {
if(!shape) {
return "unknown";
}
if(shape.length == 3) {
if(shape[2] == 3) {
return "simple";
} else {
return "filter";
}
} else if(shape.length == 4) {
if(shape[1] <= 4 && shape[2] <= 4) {
return "kernel";
}
}
return "unknown";
}
function looks_like_image_data (data) {
var shape = get_dim(data);
var res = shape_looks_like_image_data(shape);
return res;
}
function draw_grid_grayscale (canvas, pixel_size, colors, pos) {
var _width = colors[0].length;
var _height = colors.length;
canvas.width = _width * pixel_size;
canvas.height = _height * pixel_size;
var ctx = canvas.getContext("2d");
var img = ctx.createImageData(_width, _height);
var data = img.data;
var min = Infinity;
var max = -Infinity;
// finde min/max
for (var j = 0; j < _height; j++) {
for (var i = 0; i < _width; i++) {
var val = colors[j][i][pos];
if (val < min) min = val;
if (val > max) max = val;
}
}
// fülle ImageData
for (let j = 0; j < _height; j++) {
for (let i = 0; i < _width; i++) {
let val = normalize_to_rgb_min_max(colors[j][i][pos], min, max);
let idx = (j * _width + i) * 4;
data[idx] = val;
data[idx + 1] = val;
data[idx + 2] = val;
data[idx + 3] = 255;
}
}
// skaliere auf pixel_size
var tmpCanvas = document.createElement("canvas");
tmpCanvas.width = _width;
tmpCanvas.height = _height;
tmpCanvas.getContext("2d").putImageData(img, 0, 0);
ctx.imageSmoothingEnabled = false; // wichtig, sonst wird interpoliert
ctx.drawImage(tmpCanvas, 0, 0, canvas.width, canvas.height);
return true;
}
function draw_grid(canvas, pixel_size, colors, denormalize, black_and_white, onclick, multiply_by, data_hash, _class="") {
assert(typeof(pixel_size) == "number", "pixel_size must be of type number, is " + typeof(pixel_size));
if (!multiply_by) multiply_by = 1;
var drew_something = false;
var _height = colors.length;
var _width = colors[0].length;
$(canvas).attr("width", _width * pixel_size);
$(canvas).attr("height", _height * pixel_size);
if (_class) $(canvas).attr("class", _class);
if (typeof(data_hash) == "object") {
for (let name in data_hash) {
$(canvas).data(name, data_hash[name]);
}
}
if (onclick) $(canvas).attr("onclick", onclick);
var ctx = $(canvas)[0].getContext("2d");
var img = ctx.createImageData(_width, _height);
var data = img.data;
var min = 0;
var max = 0;
if (denormalize) {
for (var j = 0; j < _height; j++) {
for (var i = 0; i < _width; i++) {
var red, green, blue;
if (black_and_white) {
red = green = blue = colors[j][i];
} else {
red = colors[j][i][0];
green = colors[j][i][1];
blue = colors[j][i][2];
}
if (red > max) max = red;
if (green > max) max = green;
if (blue > max) max = blue;
if (red < min) min = red;
if (green < min) min = green;
if (blue < min) min = blue;
}
}
}
for (let j = 0; j < _height; j++) {
for (let i = 0; i < _width; i++) {
let red, green, blue;
if (black_and_white) {
red = green = blue = colors[j][i] * multiply_by;
} else {
red = colors[j][i][0] * multiply_by;
green = colors[j][i][1] * multiply_by;
blue = colors[j][i][2] * multiply_by;
}
if (denormalize) {
if (red !== undefined) red = normalize_to_rgb_min_max(red, min, max);
if (green !== undefined) green = normalize_to_rgb_min_max(green, min, max);
if (blue !== undefined) blue = normalize_to_rgb_min_max(blue, min, max);
}
var idx = (j * _width + i) * 4;
data[idx] = red;
data[idx + 1] = green;
data[idx + 2] = blue;
data[idx + 3] = 255;
drew_something = true;
}
}
// einmaliges Scaling auf pixel_size
var tmpCanvas = document.createElement("canvas");
tmpCanvas.width = _width;
tmpCanvas.height = _height;
tmpCanvas.getContext("2d").putImageData(img, 0, 0);
ctx.imageSmoothingEnabled = false;
ctx.drawImage(tmpCanvas, 0, 0, _width * pixel_size, _height * pixel_size);
return drew_something;
}
function draw_kernel(canvasElement, rescaleFactor, pixels) {
// canvasElement is the HTML canvas element where you want to draw the image
// rescaleFactor is the factor by which the image should be resized, e.g., 2 for twice the size
// pixels is a 3D array [n, m, a] where n is the height, m is the width, and a is the number of channels
scaleNestedArray(pixels);
var context = canvasElement.getContext("2d"); // Get the 2D rendering context
var [n, m, a] = [pixels.length, pixels[0].length, pixels[0][0].length]; // Destructure the dimensions
if (a === 3) {
// Draw a color image on the canvas and resize it accordingly
canvasElement.width = m * rescaleFactor;
canvasElement.height = n * rescaleFactor;
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
var [r, g, b] = pixels[i][j]; // Assuming channels are [red, green, blue]
context.fillStyle = `rgb(${r}, ${g}, ${b}`;
context.fillRect(j * rescaleFactor, i * rescaleFactor, rescaleFactor, rescaleFactor);
}
}
} else {
// Draw only the first channel
canvasElement.width = m * rescaleFactor;
canvasElement.height = n * rescaleFactor;
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
const grayscaleValue = pixels[i][j][0]; // Assuming the first channel is grayscale
context.fillStyle = `rgb(${grayscaleValue}, ${grayscaleValue}, ${grayscaleValue}`;
context.fillRect(j * rescaleFactor, i * rescaleFactor, rescaleFactor, rescaleFactor);
}
}
}
}
function draw_image_if_possible (layer, canvas_type, colors, get_canvas_object) {
var canvas = null;
try {
var ret = false;
var data_type = looks_like_image_data(colors);
if(data_type == "simple") {
if(canvas_type == "input") {
canvas = get_canvas_in_class(layer, "input_image_grid", !get_canvas_object);
} else {
canvas = get_canvas_in_class(layer, "image_grid", !get_canvas_object);
}
if(!get_canvas_object) {
$($(canvas)[0]).parent().parent().show();
}
ret = draw_grid(canvas, pixel_size, colors, 1, 0, "", "", "");
if(get_canvas_object) {
return canvas;
}
return ret;
} else if((data_type == "kernel" || canvas_type == "kernel")) {
var shape = get_dim(colors);
var canvasses = [];
for (var filter_id = 0; filter_id < shape[0]; filter_id++) {
for (var channel_id = 0; channel_id < shape[1]; channel_id++) {
canvas = get_canvas_in_class(layer, "filter_image_grid", !get_canvas_object);
if(!get_canvas_object) {
$($(canvas)[0]).parent().parent().show();
}
ret = draw_kernel(canvas, kernel_pixel_size, colors[filter_id]);
if(get_canvas_object) {
canvasses.push(canvas);
}
}
}
if(get_canvas_object) {
return canvasses;
}
return ret;
} else if(data_type == "filter") {
let shape = get_dim(colors);
let canvasses = [];
for (let k = 0; k < shape[2]; k++) {
if(canvas_type == "input") {
canvas = get_canvas_in_class(layer, "input_image_grid", !get_canvas_object);
} else {
canvas = get_canvas_in_class(layer, "image_grid", !get_canvas_object);
}
if(!get_canvas_object) {
$($(canvas)[0]).parent().parent().show();
}
ret = draw_grid_grayscale(canvas, pixel_size, colors, k);
if(get_canvas_object) {
canvasses.push(canvas);
}
}
if(get_canvas_object) {
return canvasses;
}
return ret;
}
} catch (e) {
err(e);
}
return false;
}
function recurse(a, dims) {
if (dims.length === 1) return a;
const [first, ...rest] = dims;
const result = Array.from({ length: dims[dims.length - 1] }, (_, i) =>
recurse(a.map(row => row[i]), rest)
);
return result;
}
function explain_error_msg (_err) {
if(!_err) {
return "";
}
if(typeof(_err) == "object") {
_err = _err.toString();
}
log(_err);
var explanation = "";
var nr_of_layer = model?.layers?.length;
if(!nr_of_layer) {
return "";
}
if(model && model?.layers && nr_of_layer) {
var last_layer_name = model?.layers[nr_of_layer - 1]?.name;
if(_err.includes(last_layer_name) && _err.includes("Error when checking target") && _err.includes("but got array with shape")) {
explanation = "This may mean that the number of neurons in the last layer do not conform with the data structure in the training-data-outputs.";
} else if(_err.includes("does not match the shape of the rest")) {
explanation = "Have you repeatedly pressed 'Start training'? The second one may have started while the first one was not ready, and re-downloaded images. Please reload the page.";
} else if(_err.includes("Failed to compile fragment shader")) {
explanation = "This may mean that the batch-size and/or filter-size and/or image dimension resize-sizes are too large, or your GPU memory is too low. Try disabling GPU acceleration (see General -> CPU instead of WebGL).";
} else if(_err.includes("target expected a batch of elements where each example")) {
explanation = "The last number of neurons in the last layer may not match the number of categories.<br><br>It may also be possible that you chose a wrong Loss function. If the number of neurons match, try choosing other losses, like categoricalCrossentropy, or the last layer's activation function is wrong, for classification problems it should be SoftMax.<br><br>You may also have only one category, but you need at least two.";
} else if(_err.includes("but got array with shape 0,")) {
explanation = "Have you forgotten to add your own training data?";
} else if(_err.includes("texShape is undefined")) {
explanation = "Please check if any of the output-dimensions contain '0' and if so, try to minimize the dimensionality reduction so that all zeroes disappear.";
} else if(_err.includes("info is undefined")) {
explanation = "Have you enabled debug-mode and also stopped training early? Please try disabling debug mode and re-train.<br><br>This might also be caused by calling `tf.disposeVariables()` somewhere...";
} else if(_err.includes("expects targets to be binary matrices")) {
explanation = "Try choosing another loss and metric function, like Mean Squared Error (MSE) or Mean Absolute Error (MAE).";
} else if(_err.includes("oneHot: depth must be")) {
explanation = "Try choosing another loss and metric function, like Mean Squared Error (MSE) or Mean Absolute Error (MAE).";
} else if(_err.includes("Cannot find a connection between any variable and the result of the loss function")) {
explanation = "This is probably a bug in asanAI. This may happen when the function run_neural_network is called, but the model is not compiled (e.g. the compile_model function throws an exception). You should never see this. Sorry.";
} else if (_err.includes("Input Tensors should have the same number of samples as target Tensors") || _err.includes("not defined") || _err.includes("Cannot convert")) {
explanation = "This is probably a bug in asanAI";
} else if(_err.includes("numeric tensor, but got string tensor")) {
if($("#data_origin").val() == "csv") {
explanation = "Please check your CSV-file input to remove unneeded extra characters. Neither input nor output tensors should contain any strings, but only integers and floats.";
} else {
explanation = "Are you sure your input data is numeric?";
}
} else if(_err.includes("input expected a batch of elements where each example has shape")) {
explanation = "Does the input-shape match the data?";
} else if (_err.includes("Error when checking input") && _err.includes("but got array with shape")) {
if($("#data_origin").val() == "csv") {
explanation = "Have you chosen an 'own'-data-source with CSV-files in a network with convolutional layers?";
}
}
} else {
explanation = "No layers.";
}
if(explanation.length) {
return explanation;
}
return "";
}
function layer_is_red (layer_nr) {
assert(typeof(layer_nr) == "number", "layer_nr is not a number but " + layer_nr + "(" + typeof(layer_nr) + ")");
var color = $($("div.container.layer")[layer_nr]).css("background-color");
if(color == "rgb(255, 0, 0)") {
return true;
}
return false;
}
/* This function will write the given text to the layer identification of the given number. If the text is empty, it will clear the layer identification. */
function write_layer_identification (nr, text) {
assert(typeof(nr) == "number", "write_layer_identification: first parameter nr is not a number but " + typeof(nr) + " (" + nr + ")");
assert(typeof(text) == "string", "write_layer_identification: second parameter text is not a string but " + typeof(text) + " (" + text + ")");
if(text.length) {
$($(".layer_identifier")[nr]).html(text);
} else {
$($(".layer_identifier")[nr]).html("");
}
}
function get_layer_identification (layer_idx) {
assert(typeof(layer_idx) == "number", "layer_idx is not a number");
if(model === null || model === undefined) {
model_is_ok();
return "";
}
if(!model) {
return "";
}
if(!Object.keys(model).includes("layers")) {
return "";
}
var nr_of_layer = model?.layers?.length;
if(!nr_of_layer) {
return "";
}
if(!nr_of_layer) {
return "";
}
if(layer_idx >= nr_of_layer) {
return "";
}
if(model?.layers[layer_idx] && Object.keys(model?.layers[layer_idx]).length >= 1) {
var object_keys = Object.keys(model?.layers[layer_idx]);
var new_str = "";
if(object_keys.includes("filters") && object_keys.includes("kernelSize")) {
new_str = model?.layers[layer_idx]["filters"] + "@" + model?.layers[layer_idx].kernelSize.join("x");
} else if(object_keys.includes("filters")) {
new_str = "Filters: " + model?.layers[layer_idx]["filters"];
} else if(object_keys.includes("units")) {
new_str = "Units: " + model?.layers[layer_idx]["units"];
} else if(object_keys.includes("rate")) {
new_str = "Rate: " + model?.layers[layer_idx]["rate"];
} else if(object_keys.includes("poolSize")) {
new_str = model?.layers[layer_idx]?.poolSize.join("x");
}
return new_str;
}
return "";
}
async function fetchLayerShapeStatus (layer_idx, output_shape_string, has_zero_output_shape) {
if(model && model?.layers && model?.layers?.length >= layer_idx) {
try {
model?.layers[layer_idx]?.input.shape;
} catch(e) {
void(0); dbg("Model has multi-node inputs. It should not have!!! Continuing anyway, but please, debug this!!!");
}
if (model && model?.layers && layer_idx in model?.layers) {
const this_layer = model?.layers[layer_idx];
if(this_layer) {
var shape = JSON.stringify(this_layer.getOutputAt(0).shape);
if(/((\[|,)\s*)\s*0\s*((\]|,)\s*)/.test(shape) || /\[\s*(0,?\s*?)+\s*\]/.test(shape)) {
output_shape_string = "<span style='background-color: red'>Output: " + shape + "</span>";
output_shape_string = output_shape_string.replace("null,", "");
has_zero_output_shape = true;
} else {
output_shape_string = "Output: " + shape;
output_shape_string = output_shape_string.replace("null,", "");
}
}
}
} else {
void(0); dbg(`identify_layers: layer_idx = ${layer_idx} is not in model.layers. This may happen when the model is recompiled during this step and if so, is probably harmless.`);
}
if(has_zero_output_shape) {
var basemsg = "ERROR: There are zeroes in the output shape. ";
var msg = basemsg + "The input shape will be resetted the the last known working configuration.";
disable_train();
throw new Error(msg);
} else {
enable_train();
}
return [output_shape_string, has_zero_output_shape];
}
async function identify_layers () {
var number_of_layers = $("div.container.layer").length;
if(!model) {
dbg(language[lang]["no_model_defined"]);
return;
}
if(!Object.keys(model).includes("layers") || !model?.layers?.length) {
dbg(language[lang]["the_loaded_model_has_no_layers"]);
return;
}
//console.trace();
has_zero_output_shape = false;
var failed = 0;
for (var layer_idx = 0; layer_idx < number_of_layers; layer_idx++) {
$($(".layer_nr_desc")[layer_idx]).html(layer_idx + ": ");
var new_str = get_layer_identification(layer_idx);
if(new_str != "") {
new_str = new_str + ", ";
}
var output_shape_string = "";
try {
[output_shape_string, has_zero_output_shape] = await fetchLayerShapeStatus(layer_idx, output_shape_string, has_zero_output_shape);
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
if(("" + e).includes("model is null") || ("" + e).includes("is undefined") || ("" + e).includes("reading 'getOutputAt'")) {
err("" + e);
} else {
throw new Error(e);
}
return;
}
var activation_function_string = "";
try {
if(model && model?.layers && layer_idx in model?.layers) {
var this_layer = $($(".layer")[layer_idx]);
var act = $(this_layer.find(".activation")).val();
if("" + act != "undefined") {
activation_function_string = ", " + act;
}
}
} catch (e) {
throw new Error(e);
}
if(layer_is_red(layer_idx)) {
failed++;
write_layer_identification(layer_idx, "<span class='layer_identifier_activation'></span>");
} else {
write_layer_identification(layer_idx + failed, new_str + output_shape_string + "<span class='layer_identifier_activation'>" + activation_function_string + "</span>");
}
}
if(!has_zero_output_shape) {
shown_has_zero_data = false;
}
}
function hide_unused_layer_visualization_headers () {
for (var layer_idx = 0; layer_idx < get_number_of_layers(); layer_idx++) {
hide_layer_visualization_header_if_unused(layer_idx);
}
}
function hide_layer_visualization_header_if_unused (layer) {
assert(typeof(layer) == "number", "layer is not a number");
var used = 0;
if($($(".kernel_image_grid_div")[layer]).css("display") != "none") {
used = 1;
}
if($($(".output_image_grid_div")[layer]).css("display") != "none") {
used = 1;
}
if($($(".input_image_grid_div")[layer]).css("display") != "none") {
used = 1;
}
if(used == 0) {
$($(".layer_data")[layer]).hide();
}
}
async function add_layer_debuggers () {
$("#datalayers").html("");
$(".layer_data").html("");
if(!model) {
if(finished_loading) {
dbg(language[lang]["no_model_found"]);
}
return;
}
if(!model?.layers) {
if(finished_loading) {
dbg(language[lang]["no_layers_found"]);
}
}
try {
if(!model) {
return;
}
if(!model?.layers) {
return;
}
var nr_of_layer = model?.layers?.length;
if(!nr_of_layer) {
return;
}
for (var layer_idx = 0; layer_idx < nr_of_layer; layer_idx++) {
if(get_methods(model?.layers[layer_idx]).includes("original_apply_real")) {
model.layers[layer_idx].apply = model.layers[layer_idx].original_apply_real;
}
model.layers[layer_idx].original_apply_real = model.layers[layer_idx].apply;
var code = `model.layers[${layer_idx}].apply = function (inputs, kwargs) {
if (${layer_idx} == 0) {
layer_states_saved = {}
}
var output = model?.layers[${layer_idx}]?.original_apply_real(inputs, kwargs);
var shown_layer_debuggers = false;
if(!disable_layer_debuggers) {
if($("#show_layer_data").is(":checked")) {
$("#layer_visualizations_tab").show();
draw_internal_states(${layer_idx}, inputs, output);
shown_layer_debuggers = true;
}
}
if(!shown_layer_debuggers) {
$("#layer_visualizations_tab").hide();
}
const synced_output = array_sync(output);
const synced_input = array_sync(inputs[0]);
var this_layer_data = {
input: synced_input,
output: synced_output,
model_uuid: model.uuid
};
layer_states_saved["${layer_idx}"] = this_layer_data;
if(started_training) {
if(!Object.keys(neuron_outputs).includes("${layer_idx}")) {
neuron_outputs["${layer_idx}"] = {input: [], output: []};
}
neuron_outputs["${layer_idx}"]["input"].push(synced_input);
neuron_outputs["${layer_idx}"]["output"].push(synced_output);
}
return output;
}`;
try {
eval(code);
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
if(("" + e).includes("already disposed")) {
wrn("" + e);
} else {
throw new Error("" + e);
}
}
}
} catch (e) {
err(e);
}
if(!input_shape_is_image()) {
await predict_own_data_and_repredict();
}
}
function show_and_append_layer_divs (layer_div, layer) {
if(!layer_div) {
err(`[show_and_append_layer_divs] layer_div was falsy`);
return;
}
try {
layer_div.show();
layer_div.append("<div class='data_flow_visualization input_layer_header' style='display: none' id='layer_" + layer + "_input'><h4>Input:</h4></div>");
layer_div.append("<div class='data_flow_visualization weight_matrix_header' style='display: none' id='layer_" + layer + "_kernel'><h4>" + language[lang]["weight_matrices"] + ":</h4></div>");
layer_div.append("<div class='data_flow_visualization output_header' style='display: none' id='layer_" + layer + "_output'><h4>Output:</h4></div>");
layer_div.append("<div class='data_flow_visualization equations_header' style='display: none' id='layer_" + layer + "_equations'></div>");
} catch (e) {
err(`[show_and_append_layer_divs] ${e}`);
}
}
function show_intermediate_representations(canvas_input, canvas_output, canvas_kernel, input, kernel, output, layer) {
if(!canvas_input) {
err(`[show_intermediate_representations] canvas_input was empty`);
return;
}
if(!canvas_kernel) {
err(`[show_intermediate_representations] canvas_kernel was empty`);
return;
}
if(!canvas_output) {
err(`[show_intermediate_representations] canvas_output was empty`);
return;
}
for (var j = 0; j < canvas_input.length; j++) {
for (var canvas_idx = 0; canvas_idx < canvas_output.length; canvas_idx++) {
var img_output = canvas_output[canvas_idx];
if(Object.keys(canvas_kernel).includes(canvas_idx + "")) {
var img_kernel = canvas_kernel[canvas_idx * 3];
if(layer == 0) {
input.append(canvas_input[j * 3]).show();
}
kernel.append(img_kernel).show();
}
output.append(img_output).show();
}
}
return [input, kernel, output];
}
function draw_internal_states (layer, inputs, applied) {
typeassert(layer, int, "layer");
typeassert(inputs, array, "inputs");
var number_of_items_in_this_batch = inputs[0].shape[0];
if($(".layer_data").length != get_number_of_layers()) {
var inner_html = "";
for (var layer_idx = 0; layer_idx < get_number_of_layers(); layer_idx++) {
inner_html += "<div class='layer_data'></div>";
}
$("#layer_visualizations_tab").html(inner_html);
}
for (var batchnr = 0; batchnr < number_of_items_in_this_batch; batchnr++) {
var input_data = array_sync(inputs[0])[batchnr];
var output_data = array_sync(applied)[batchnr];
var layer_div = $($(".layer_data")[layer]);
if(batchnr == 0) {
layer_div.append("<h1>Layer data flow</h1>");
}
layer_div.html("<h3 class=\"data_flow_visualization layer_header\">Layer " + layer + " — " + $($(".layer_type")[layer]).val() + " " + get_layer_identification(layer) + "</h3>").hide();
show_and_append_layer_divs(layer_div, layer);
var input = $("#layer_" + layer + "_input");
var kernel = $("#layer_" + layer + "_kernel");
var output = $("#layer_" + layer + "_output");
var equations = $("#layer_" + layer + "_equations");
show_layer_visualization_tab();
var kernel_data = [];
if(Object.keys(model?.layers[layer]).includes("kernel")) {
if(model?.layers[layer]?.kernel?.val?.shape?.length == 4) {
var ks_x = 0;
var ks_y = 1;
var number_filters = 2;
var filters = 3;
kernel_data = tidy(() => {
return array_sync(tf_transpose(model?.layers[layer]?.kernel?.val, [filters, ks_x, ks_y, number_filters]));
});
}
}
var canvas_input = draw_image_if_possible(layer, "input", input_data, 1);
var canvas_kernel = draw_image_if_possible(layer, "kernel", kernel_data, 1);
var canvas_output = draw_image_if_possible(layer, "output", output_data, 1);
if(canvas_output.length && canvas_input.length) {
[input, kernel, output] = show_intermediate_representations(canvas_input, canvas_output, canvas_kernel, input, kernel, output, layer);
} else if (canvas_output.length && canvas_input.nodeName == "CANVAS") {
[input, kernel, output] = visualize_layer_canvases_simple(canvas_input, canvas_kernel, canvas_output, input, kernel, output, layer);
} else {
[input, output, equations] = show_layer_state_or_data(canvas_input, canvas_output, output_data, input, output, equations, layer);
}
}
if(number_of_items_in_this_batch) {
$("#layer_visualizations_tab").show();
} else {
$("#layer_visualizations_tab").hide();
}
}
function show_layer_state_or_data (canvas_input, canvas_output, output_data, input, output, equations, layer) {
if(canvas_input.nodeName == "CANVAS") {
if(layer == 0) {
input.append(canvas_input).show();
}
if(canvas_output.nodeName == "CANVAS") {
let img_output = canvas_output;
output.append(img_output).show();
}
} else {
if(get_shape_from_array(output_data).length == 1 && !$("#show_raw_data").is(":checked")) {
let h = visualizeNumbersOnCanvas(output_data);
equations.append(h).show();
} else {
let h = array_to_html(output_data);
equations.append(h).show();
}
}
return [input, output, equations];
}
function visualize_layer_canvases_simple (canvas_input, canvas_kernel, canvas_output, input, kernel, output, layer) {
if(canvas_output) {
for (var canvas_idx = 0; canvas_idx < canvas_output.length; canvas_idx++) {
var img_output = canvas_output[canvas_idx];
if(layer == 0) {
input.append(canvas_input).show();
}
if(Object.keys(canvas_kernel).includes(canvas_idx + "")) {
var img_kernel = canvas_kernel[canvas_idx * 3];
kernel.append(img_kernel).show();
}
output.append(img_output).show();
}
}
return [input, kernel, output];
}
function get_empty_default_trace (name) {
return {
x: [],
y: [],
type: "scatter",
name: name
};
}
async function get_live_tracking_on_batch_end (global_model_name, max_epoch, x_data_json, y_data_json, show_loss, append_to_id) {
var id = uuidv4();
var onBatchEnd = function (epoch, logs) {
if(typeof(old_onEpochEnd) == "function") {
old_onEpochEnd(epoch, logs);
}
try {
var current_epoch = epoch + 1;
if(current_epoch == 1) {
$(`#${append_to_id}`).html("");
$(`<div id='${id}_training_data_graph'></div>`).appendTo($(`#${append_to_id}`));
}
var real_trace = get_empty_default_trace("Ground Truth");
var predicted_trace = get_empty_default_trace("Prediction");
var x_data, y_data;
try {