-
Notifications
You must be signed in to change notification settings - Fork 1
/
predict.js
2090 lines (1652 loc) · 50.8 KB
/
predict.js
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";
async function __predict (data, __model, recursion = 0) {
if(!data) {
err("[__predict] data undefined");
return;
}
if(recursion > 2) {
err("[__predict] too many retries for predict.");
return;
}
if(!__model) {
__model = model;
}
if(!__model) {
err("[__predict] Cannot predict without a model");
return;
}
var res;
try {
res = __model.predict(data);
} catch (e) {
if(Object.keys(e).includes("message")) {
e = "" + e.message;
}
if(("" + e).includes("but got array with shape")) {
var dis = data.shape.join(", ");
if(!__model || Object.keys(__model).includes("input")) {
var mis = __model.input.shape.join(", ");
dbg(sprintf(language[lang]["wrong_input_shape_for_prediction_data_x_model_y"], dis, mis));
} else {
dbg(sprintf(language[lang]["wrong_input_shape_for_prediction_data_x_model_y"], dis, "not determinable"));
}
await dispose(data);
return;
} else if(("" + e).includes("is already disposed") && ("" + e).includes("LayersVariable")) {
dbg(language[lang]["model_was_already_disposed"]);
await dispose(data);
return;
} else {
await compile_model();
if(warn_if_tensor_is_disposed(data)) {
res = await __predict(data, model, recursion + 1);
} else {
err(language[lang]["cannot_predict_since_the_data_about_to_be_predicted_is_already_disposed"]);
await dispose(data);
return;
}
}
}
var res_sync = array_sync(res);
while (get_shape_from_array(res_sync).length > 1) {
res_sync = res_sync.flat();
}
var output_contains_nan = false;
for (var k = 0; k < res_sync.length; k++) {
if(output_contains_nan) {
continue;
}
if(isNaN(res_sync[k])) {
output_contains_nan = true;
}
}
if(output_contains_nan) {
err("[__predict] Output contains NaN");
}
return res;
}
async function switch_to_next_camera_predict () {
webcam_id++;
webcam_id = webcam_id % (webcam_modes.length);
await show_webcam(1);
}
async function get_label_data () {
if(($("#data_origin").val() == "image" || await input_shape_is_image()) && $("#data_origin").val() == "default") {
let imageData = await get_image_data(1, 0, {
title: language[lang]["loading_images_into_memory"],
html: language[lang]["this_may_take_a_while"]
}, 0, 1);
await reset_labels();
var category_counter = 0;
var keys = [];
var new_labels = [];
for (let [key, value] of Object.entries(imageData)) {
keys.push(key);
}
await set_labels(keys);
}
}
function load_file (event) {
try {
var files = event.target.files;
var $output = $("#uploaded_file_predictions");
var uploaded_file_pred =
"<span class='single_pred'>\n" +
`<img width='${width}' height='${height}' src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" alt="Image" class="uploaded_file_img"\n>` +
"<br>" +
"<span class=\"uploaded_file_prediction\"></span>" +
"</span>\n";
var repeated_string = "";
for (var i = 0; i < files.length; i++) {
repeated_string += uploaded_file_pred;
}
$output.html(repeated_string);
for (var i = 0; i < files.length; i++) {
$($(".single_pred")[i]).removeAttr("src");
var img_elem = $($(".uploaded_file_img")[i])[0];
var async_func;
eval(`async_func = async function() {
var _img_elem = $($(".uploaded_file_img")[${i}])[0];
URL.revokeObjectURL(_img_elem.src);
var _result = await predict(_img_elem);
var $set_this = $($(".uploaded_file_prediction")[${i}]);
assert($set_this.length, \`.uploaded_file_prediction[${i}] not found!\`);
//console.log("_img_elem:", _img_elem, "i:", ${i}, "$set_this:", $set_this, "_result:", _result, "_result md5:", await md5(_result));
$set_this.html(_result).show();
$(".only_show_when_predicting_image_file").show();
}`);
img_elem.src = URL.createObjectURL(files[i]);
img_elem.onload = async_func;
}
$output.show();
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
assert(false, e);
}
}
function _predict_error (e) {
err(e);
console.trace();
$("#prediction").hide();
$("#predict_error").html("" + e).show();
$("#example_predictions").html("");
$(".show_when_has_examples").hide();
}
function _divide_img_tensor (tensor_img) {
var divide_by = parse_float($("#divide_by").val());
if(divide_by == 1) {
return tensor_img;
}
try {
tensor_img = tidy(() => {
return divNoNan(tensor_img, divide_by);
});
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
_predict_error(e);
}
return tensor_img;
}
async function _get_tensor_img(item) {
var tensor_img = null;
try {
tensor_img = await tidy(() => {
return tf_to_float(expand_dims(
resize_image(_divide_img_tensor(fromPixels(item)), [height, width])
));
});
} catch (e) {
void(0); log("item:", item, "width:", width, "height:", height, "error:", e);
if(Object.keys(e).includes("message")) {
e = e.message;
}
_predict_error(e);
return null;
}
return tensor_img;
}
function set_item_natural_width (item) {
if(document.body === null) {
wrn("[set_item_natural_width] document.body is null!");
return;
}
try {
var $item = $(item);
assert($item.length > 0, "$item is empty");
var element_vanilla_js = $item[0];
$item.prop("width", element_vanilla_js.naturalWidth);
$item.prop("height", element_vanilla_js.naturalHeight);
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
_predict_error("" + e);
return false;
}
return true;
}
async function predict_demo (item, nr, tried_again = 0) {
if(has_zero_output_shape) {
dbg("[predict_demo] has_zero_output_shape is true");
return;
}
while ((is_hidden_or_has_hidden_parent($("#predict_tab")) && finished_loading)) {
await delay(200);
}
//var xpath = get_element_xpath(item);
//tf.engine().startScope("scope_" + xpath);
var new_tensor_img;
try {
if(labels.length == 0) {
await get_label_data();
}
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
_predict_error("" + e);
return;
}
if(!set_item_natural_width(item)) {
err("[predict_demo] Setting item to natural height failed. Returning.");
return;
}
//log("Tensors 4: " + tf.memory()["numTensors"]);
if(item.width == 0) {
//log("item width is 0, not predicting:", item);
return;
}
assert(!!item, "item must at least be true");
assert(width > 0, "width is not larger than 0");
assert(height > 0, "height is not larger than 0");
var tensor_img = await _get_tensor_img(item);
if(!tensor_img) {
err("[predict_demo] tensor_img was empty");
await dispose(tensor_img);
return;
}
if(!model) {
wrn("[predict_demo] Model is undefined");
return;
}
if(!Object.keys(model.layers).includes("0")) {
wrn("[predict_demo] Does not include first layer");
return;
}
while (!tf.backend()) {
await delay(100);
}
if(!model) {
if(finished_loading) {
err("[predict_demo] No model");
}
await dispose(tensor_img);
return;
}
if(!tensor_shape_matches_model(tensor_img)) {
dbg("[predict_demo] Model input shape: ", model.input.shape, "Tensor-Img-shape:", tensor_img.shape);
await dispose(tensor_img);
return;
}
try {
await _run_predict_and_show(tensor_img, nr);
await dispose(tensor_img);
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
void(0); err("Error (101): " + e);
log("================================= tensor_img:", tensor_img);
_predict_error("" + e);
if(tried_again) {
return;
}
await dispose(tensor_img);
await dispose(new_tensor_img);
return await predict_demo(item, nr, 1);
}
hide_unused_layer_visualization_headers();
change_output_and_example_image_size();
allow_editable_labels();
await dispose(tensor_img);
await dispose(new_tensor_img);
//tf.engine().endScope("scope_" + xpath);
await nextFrame();
}
async function _run_predict_and_show (tensor_img, nr) {
try {
if(tensor_img.isDisposedInternal) {
dbg("[_run_predict_and_show] Tensor was disposed internally", tensor_img);
console.trace();
return;
}
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
assert(false, e);
}
if(!tensor_shape_matches_model(tensor_img)) {
dbg("[_run_predict_and_show] Tensor shape does not match model shape");
return;
}
var predictions_tensor;
try {
predictions_tensor = await __predict(tensor_img);
if(!predictions_tensor) {
dbg(language[lang]["predictions_tensor_was_empty"]);
return;
}
warn_if_tensor_is_disposed(predictions_tensor);
await _predict_result(predictions_tensor, nr, 0);
warn_if_tensor_is_disposed(predictions_tensor);
await draw_heatmap(predictions_tensor, tensor_img);
await dispose(predictions_tensor);
} catch (e) {
if(("" + e).includes("already disposed")) {
dbg("[_run_predict_and_show] Tensors already disposed. Probably the model was recompiled while predicting.");
} else if(("" + e).includes("but got array with shape")) {
dbg("[_run_predict_and_show] Prediction got wrong tensor shape. This may be harmless when you just switched models, otherwise, it indicates a bug.");
} else if(("" + e).includes("code is undefined")) {
err(e + ". This may mean that the whole document was deleted!!!");
} else if(("" + e).includes("predictions is null")) {
err("" + e);
} else if(("" + e).includes("Either strides or dilations must be 1")) {
for (var i = 0; i < $("#layers_container").length; i++) {
set_layer_background(i, "red");
set_model_layer_warning(i, "" + e);
}
} else {
err("" + e);
console.trace();
}
}
for (var i = 0; i < $("#layers_container").length; i++) {
set_layer_background(i, "");
set_model_layer_warning(i, "");
}
await dispose(predictions_tensor);
}
async function _predict_result(predictions_tensor, nr, _dispose = 1) {
var desc = $($(".predict_demo_result")[nr]);
desc.html("");
if(model.outputShape.length == 4) {
await _predict_image(predictions_tensor, desc);
} else if(model.outputShape.length == 2) {
await _predict_table(predictions_tensor, desc);
} else {
var latex = arbitrary_array_to_latex(array_sync(predictions_tensor));
desc.html(latex);
}
if(_dispose) {
await dispose(predictions_tensor);
}
}
async function _predict_image (predictions_tensor, desc) {
try {
var predictions_tensor_transposed = tf_transpose(predictions_tensor, [3, 1, 2, 0]);
var predictions = array_sync(predictions_tensor_transposed);
var pxsz = 1;
var largest = Math.max(predictions_tensor_transposed.shape[1], predictions_tensor_transposed.shape[2]);
assert(typeof(largest) == "number", "_predict_image: largest is not a number");
var max_height_width = Math.min(100, Math.floor(window.innerWidth / 5));
assert(typeof(max_height_width) == "number", "_predict_image: max_height_width is not a number");
while ((pxsz * largest) < max_height_width) {
pxsz += 1;
}
scaleNestedArray(predictions);
for (var i = 0; i < predictions.length; i++) {
var canvas = $("<canvas/>", {class: "layer_image"}).prop({
width: pxsz * predictions_tensor.shape[2],
height: pxsz * predictions_tensor.shape[1],
});
desc.append(canvas);
//draw_grid (canvas, pixel_size, colors, denormalize, black_and_white, onclick, multiply_by, data_hash, _class="") {
//log("predictions[i]:", predictions[i]);
var res = draw_grid(canvas, pxsz, predictions[i], 1, 1);
}
await dispose(predictions_tensor_transposed);
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
assert(false, e);
}
}
function scaleNestedArray(arr) {
assert(Array.isArray(arr), "scaleNestedArray input parameter is not Array, but " + typeof(arr));
// Find the minimum and maximum values in the nested array
let min = Number.MAX_VALUE;
let max = Number.MIN_VALUE;
function findMinMax(arr) {
for (let item of arr) {
if (Array.isArray(item)) {
findMinMax(item);
} else {
if (item < min) min = item;
if (item > max) max = item;
}
}
}
findMinMax(arr);
// Scale the values
function scaleValue(value) {
return (value - min) * (255 / (max - min));
}
function scaleNested(arr) {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
scaleNested(arr[i]);
} else {
arr[i] = scaleValue(arr[i]);
}
}
}
scaleNested(arr);
}
function get_show_green () {
var last_layer_activation = get_last_layer_activation_function();
var show_green = last_layer_activation == "softmax" ? 1 : 0;
return show_green;
}
async function _predict_table(predictions_tensor, desc) {
if(!predictions_tensor) {
wrn("[_predict_table] predictions_tensor was empty");
return;
}
try {
var predictions = tidy(() => { return predictions_tensor.dataSync(); });
if(predictions.length) {
var max_i = 0;
var max_probability = -9999999;
for (let i = 0; i < predictions.length; i++) {
var probability = predictions[i];
if(probability > max_probability) {
max_probability = probability;
max_i = i;
}
}
var fullstr = "";
fullstr += "<table class='predict_table'>";
for (let i = 0; i < predictions.length; i++) {
var label = labels[i % labels.length];
var probability = predictions[i];
var w = Math.floor(probability * 50);
fullstr += _predict_table_row(label, w, max_i, probability, i);
}
fullstr += "</table>";
if(desc) {
desc.html(fullstr);
}
}
$("#predict_error").hide();
$("#predict_error").html("");
return fullstr;
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
wrn("" + e);
}
}
function _predict_table_row (label, w, max_i, probability, i) {
var str = "";
if(show_bars_instead_of_numbers()) {
str = "<tr><td class='label_element'>" + label + "</td><td><span class='bar'><span style='width: " + w + "px'></span></span></td></tr>";
if(i == max_i && get_show_green()) {
//str = "<b class='best_result'>" + str + "</b>";
str = "<tr><td class='label_element'>" + label + "</td><td><span class='bar'><span class='highest_bar' style='width: " + w + "px'></span></span></td></tr>";
}
} else {
str = "<tr><td class='label_element'>" + label + "</td><td>" + probability + "</td></tr>";
if(i == max_i && get_show_green()) {
str = "<tr><td class='label_element'>" + label + "</td><td><b class='best_result label_input_element'>" + probability+ "</b></td></tr>";
}
}
return str;
}
function _prepare_data(item, original_item) {
try {
var data = "";
var regex_space_start = /^\s+/ig;
var regex_space_end = /\s+$/ig;
var regex_comma = /,?\s+/ig;
item = item.replaceAll(regex_space_start, "");
item = item.replaceAll(regex_space_end, "");
item = item.replaceAll(regex_comma, ", ");
item = item.replaceAll(/\btrue\b/ig, "1");
item = item.replaceAll(/\bfalse\b/ig, "0");
if(!item.startsWith("[")) {
item = "[" + item + "]";
}
data = eval(item);
if(!original_item.startsWith("[[")) {
var data_input_shape = get_shape_from_array(data);
var input_shape = model.layers[0].input.shape;
if(input_shape[0] === null) {
var original_input_shape = input_shape;
input_shape = remove_empty(input_shape);
if(input_shape.length != data_input_shape.length) {
data = [data];
}
}
}
return data;
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
assert(false, e);
}
}
function number_of_elements_in_tensor_shape (shape) {
try {
var required_elements = 1;
for (var i = 0; i < shape.length; i++) {
if(shape[i] !== null) {
required_elements *= shape[i];
}
}
return required_elements;
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
assert(false, e);
}
}
async function predict (item, force_category, dont_write_to_predict_tab, pred_tab = "prediction") {
$("#" + pred_tab).html("").show();
$("#predict_error").html("").hide();
var predictions = [];
var str = "";
var ok = 1;
var estr = "";
var predict_data = null;
try {
var is_image_prediction = await input_shape_is_image();
var has_html = false;
if(is_image_prediction) {
try {
predict_data = tf.tidy(() => {
var res = tf_to_float(
expand_dims(
resize_image(
fromPixels(item),
[height, width]
)
)
);
return res;
});
//console.log(predict_data);
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
await dispose(predict_data);
if(("" + e).includes("Expected input shape")) {
dbg("" + e);
} else {
l("" + e);
console.trace();
}
}
} else {
var data = "";
if(item.startsWith("# shape:")) {
data = [array_sync(numpy_str_to_tf_tensor(item, 0))];
} else {
var original_item = item;
if(item.match(/^\s*$/)) {
dbg("[predict] Not trying to predict empty custom item");
return;
}
data = _prepare_data(item, original_item);
}
predict_data = tensor(data);
}
if(predict_data["isDisposedInternal"]) {
err("[predict] predict_data is already disposed!");
return;
}
if(!predict_data) {
await dispose(predict_data);
var str = "Empty predict data, not predicting";
l(str);
return str;
} else if(predict_data.shape.includes("0") || predict_data.shape.includes(0)) {
await dispose(predict_data);
var str = "Dredict data tensor shape contains 0, not predicting";
l(str);
return str;
}
var divide_by = parse_float($("#divide_by").val());
if(divide_by != 1) {
predict_data = tidy(() => {
var res = divNoNan(predict_data, divide_by);
return res;
});
}
if(predict_data["isDisposedInternal"]) {
err("[predict] predict_data is already disposed!");
return;
}
if(!model.input) {
err(language[lang]["model_has_no_input"]);
return;
}
var mi = model.input.shape;
if(!mi) {
err(language[lang]["cannot_get_model_input_shape"]);
return;
}
mi[0] = 1;
var predictions_tensor = null;
$("#predict_error").html("").hide();
try {
if(predict_data["isDisposedInternal"]) {
err(`[predict] ${language[lang]["predict_data_is_already_disposed"]}!`);
return;
}
var prod_pred_shape = number_of_elements_in_tensor_shape(predict_data.shape);
var prod_mod_shape = number_of_elements_in_tensor_shape(mi);
//log(`prod_pred_shape: ${prod_pred_shape}, prod_mod_shape: ${prod_mod_shape}`);
if(prod_pred_shape == prod_mod_shape) {
var model_shape_one = mi;
if(model_shape_one[0] === null) { model_shape_one[0] = 1; }
if(predict_data.shape.join(",") != model_shape_one) {
predict_data = tidy(() => {
var old_tensor = predict_data;
//console.log("A: changing old_tensor shape [" + old_tensor.shape.join(", ") + "] to [" + model_shape_one.join(", ") + "]");
var new_data = tf_reshape(old_tensor, model_shape_one);
//console.debug("Predict data input shape: [" + predict_data.shape.join(",") + "]");
return new_data;
});
}
if(predict_data["isDisposedInternal"]) {
err(`[predict] ${language[lang]["predict_data_is_already_disposed"]}!`);
return;
}
} else if(Math.max(prod_pred_shape, prod_mod_shape) % Math.min(prod_mod_shape, prod_pred_shape) == 0) {
var _max = Math.max(prod_pred_shape, prod_mod_shape);
var _min = Math.min(prod_pred_shape, prod_mod_shape);
var _modulo = _max % _min;
var elements = (_max - _modulo) / _min;
var model_shape_one = mi;
model_shape_one[0] = elements;
//console.log(model_shape_one);
if(predict_data.shape.join(",") != model_shape_one) {
predict_data = tidy(() => {
var old_tensor = predict_data;
//console.log("B: changing old_tensor shape [" + old_tensor.shape.join(", ") + "] to [" + model_shape_one.join(", ") + "]");
var new_data = tf_reshape(old_tensor, model_shape_one);
//console.debug("Predict data input shape: [" + predict_data.shape.join(",") + "]");
return new_data;
});
}
if(predict_data["isDisposedInternal"]) {
err(`[predict] ${language[lang]["predict_data_is_already_disposed"]}!`);
return;
}
} else {
await dispose(predict_data);
var pd_nr = number_of_elements_in_tensor_shape(predict_data.shape);
var is_nr = number_of_elements_in_tensor_shape(mi);
throw(`Could not reshape data for model (predict_data.shape/model.input.shape: [${pd_nr}], [${is_nr}]`);
return;
}
if(predict_data["isDisposedInternal"]) {
err(`[predict] ${language[lang]["predict_data_is_already_disposed"]}!`);
return;
}
try {
predictions_tensor = await __predict(predict_data);
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
err("" + e);
}
await dispose(predict_data);
} catch (e) {
dbg(`[PREDICT] Model input shape [${mi.join(", ")}], tensor shape [${predict_data.shape.join(", ")}], tensor_shape_matches_model() = ${tensor_shape_matches_model(predict_data)}`);
if(("" + e).includes("got array with shape")) {
err("" + e);
$("#predict_error").html(("" + e).replace(/^(?:Error:\s*)*/, "Error:")).show();
} else if(("" + e).includes("Could not reshape")) {
throw new Error("" + e);
} else {
var err_msg = `Error 1201: ${e}, predict data shape: [${predict_data.shape.join(", ")}], model input shape: [${model.input.shape.filter(n => n).join(",")}]`;
$("#predict_error").html(err_msg).show();
err(err_msg);
}
ok = 0;
return;
}
warn_if_tensor_is_disposed(predictions_tensor);
await draw_heatmap(predictions_tensor, predict_data);
predictions = predictions_tensor.dataSync();
//log(predictions);
if(!is_image_prediction && labels.length == 0) {
str = "[" + predictions.join(", ") + "]";
pred_tab = "prediction_non_image";
$("#" + pred_tab).html("");
} else {
var desc = $("#pred_tab");
if(desc.length == 0) {
desc = $(item).after("<span class='predict_autogenerated_images'></span>");
}
if(desc.length == 0) {
dbg("[predict] desc is none");
} else {
desc = desc[0];
desc = $(desc);
if(model.outputShape.length == 4) {
var pxsz = 1;
draw_multi_channel(predictions_tensor, desc, pxsz);
} else {
if(predictions.length) {
var r = await _predict_table(predictions_tensor, desc);
if(r) {
str += r;
}
} else {
dbg("[predict] No predict tensor found");
}
}
}
}
if(is_image_prediction || labels.length) {
$("#" + pred_tab).append(str).show();
} else {
var latex = arbitrary_array_to_latex(array_sync(predictions_tensor));
$("#" + pred_tab).append(latex).show();
temml.render($("#prediction_non_image").text(), $("#prediction_non_image")[0]);
}
$("#predict_error").html("").hide();
await dispose(predict_data);
await dispose(predictions_tensor);
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
await dispose(predict_data);
estr = "" + e;
if(!estr.includes("yped")) {
if(!estr.includes("Expected input shape")) {
_predict_error("" + e);
} else {
$("#prediction_non_image").html(estr);
}
} else {
err(e);
}
ok = 0;
}
allow_editable_labels();
if(ok) {
l(language[lang]["prediction_done"]);
} else {
if(estr) {
l(estr);
$("#prediction_non_image").html("<span style='color: red'>" + estr + "</span>");
} else {
err(`${language[lang]["error"]}: ${language[lang]["prediction_failed"]}`);
}
}
await dispose(predict_data);
return str;
}
async function show_prediction (keep_show_after_training_hidden, dont_go_to_tab) {
if(skip_predictions) {
return;
}
if(!model) {
err("[show_prediction] No model given for show_prediction");
$(".show_when_has_examples").hide();
$("#example_predictions").hide();
$(".show_when_predicting").hide();
return;
}
$(".show_when_predicting").show();
$(".show_when_has_examples").hide();
hide_unused_layer_visualization_headers();
if(!keep_show_after_training_hidden) {
$(".show_after_training").show();
}
if(!$("#data_origin").val() == "default") {