-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrain.js
1639 lines (1303 loc) · 44.2 KB
/
train.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 gui_in_training (set_started_training=1) {
if(set_started_training) {
started_training = true;
}
await disable_everything();
favicon_spinner();
await write_descriptions();
await reset_cached_loaded_images();
}
async function gui_not_in_training (set_started_training=1) {
if(set_started_training) {
started_training = false;
}
$(".train_neural_network_button").html("<span class='TRANSLATEME_start_training'></span>").removeClass("stop_training").addClass("start_training");
await update_translations();
favicon_default();
try {
if (!tf.engine().state.activeScope === null) {
tf.engine().endScope();
}
} catch (e) {
log("[gui_not_in_training] " + e);
}
await enable_everything();
$(".show_after_training").show();
$("#program_looks_at_data_span").hide();
await reset_cached_loaded_images();
}
function reset_gui_before_training () {
prev_layer_data = [];
$(".reset_before_train_network").html("");
$("#percentage").html("");
$("#percentage").show();
$(".input_image_grid").html("");
$(".output_image_grid").html("");
reset_photo_gallery();
reset_summary();
}
async function train_neural_network () {
if(model === null || model === undefined || typeof(model) != "object" || !Object.keys(model).includes("layers")) {
await gui_not_in_training();
model = await create_model();
await compile_model();
return;
}
restart_fcnn(); // await not possible i think
if(started_training) {
show_overlay(language[lang]["stopped_training"] + " — " + language[lang]["this_may_take_a_while"] + "...");
if($("#show_grad_cam").is(":checked")) {
l(language[lang]["you_cannot_use_gradcam_and_internal_states_together"]);
$("#show_grad_cam").prop("checked", false).prop("disabled", true).trigger("change");
}
stop_downloading_data = true;
if(model.isTraining) {
model.stopTraining = true;
model.stopTraining = true;
}
set_document_title(original_title);
await gui_not_in_training();
$(".overlay").remove();
l(language[lang]["stopped_training"]);
} else {
l(language[lang]["started_training"]);
stop_downloading_data = false;
$("#show_grad_cam").prop("disabled", false);
last_training_time = Date.now();
await gui_in_training();
training_logs_batch = {
"loss": {
"x": [],
"y": [],
"type": get_scatter_type(),
"mode": get_plotly_type(),
"name": "Loss"
}
};
training_logs_epoch = {
"loss": {
"x": [],
"y": [],
"type": get_scatter_type(),
"mode": get_plotly_type(),
"name": "Loss"
}
};
last_batch_time = 0;
time_per_batch = {
"time": {
"x": [],
"y": [],
"type": get_scatter_type(),
"mode": get_plotly_type(),
"name": "Time per batch (in seconds)"
}
};
training_memory_history = {
numBytes: {
"x": [],
"y": [],
"type": get_scatter_type(),
"mode": get_plotly_type(),
"name": "RAM (MB)"
},
numBytesInGPU: {
"x": [],
"y": [],
"type": get_scatter_type(),
"mode": get_plotly_type(),
"name": "GPU (MB)"
},
numTensors: {
"x": [],
"y": [],
"type": get_scatter_type(),
"mode": get_plotly_type(),
"name": "Number of Tensors"
}
};
reset_gui_before_training();
$("#percentage").html("");
$("#percentage").hide();
await run_neural_network();
await show_tab_label("predict_tab_label", jump_to_interesting_tab());
await enable_everything();
await show_prediction();
}
await write_descriptions();
await write_model_to_latex_to_page();
await save_current_status();
}
function get_key_by_value(_object, value) {
try {
var res = Object.keys(_object).find(key => _object[key] === value);
return res;
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
assert(false, e);
}
}
async function get_model_data (optimizer_name_only) {
if(global_model_data) {
var model_data_tensors = find_tensors_with_is_disposed_internal(global_model_data);
for (var i = 0; i < model_data_tensors.length; i++) {
await dispose(model_data_tensors[i]);
}
}
var loss = $("#loss").val();
var optimizer_type = $("#optimizer").val();
var metric_type = $("#metric").val();
if(Object.values(metric_shortnames).includes(metric_type)) {
metric_type = get_key_by_value(metric_shortnames, metric_type);
}
var epochs = $("#epochs").val();
var batchSize = $("#batchSize").val();
var validationSplit = $("#validationSplit").val();
var divide_by = $("#divide_by").val();
if(looks_like_number(epochs)) {
epochs = parse_int(epochs);
} else {
finished_loading && wrn("#epochs doesnt look like a number");
}
if(looks_like_number(batchSize)) {
batchSize = parse_int(batchSize);
} else {
finished_loading && wrn("#batchSize doesnt look like a number");
}
if(looks_like_number(validationSplit)) {
validationSplit = parse_int(validationSplit);
} else {
finished_loading && wrn("#validation_split doesnt look like a number");
}
if(looks_like_number(divide_by)) {
divide_by = parse_float(divide_by);
} else {
finished_loading && wrn("#divide_by doesnt look like a number");
}
global_model_data = {
loss: loss,
optimizer_name: optimizer_type,
optimizer: optimizer_type,
metrics: metric_type,
metric: metric_type,
epochs: epochs,
batchSize: batchSize,
validationSplit: validationSplit,
divide_by: divide_by,
labels: labels
};
if(!is_hidden_or_has_hidden_parent($("#height"))) {
global_model_data["width"] = width;
global_model_data["height"] = height;
}
var optimizer_data_names = model_data_structure[optimizer_type];
for (var i = 0; i < optimizer_data_names.length; i++) {
var element_name = optimizer_data_names[i] + "_" + optimizer_type;
var $element_field = $("#" + element_name);
var element_val = $element_field.val();
global_model_data[optimizer_data_names[i]] = parse_float(element_val);
}
var optimizer_constructors = {
"adadelta": "adadelta(global_model_data['learningRate'], global_model_data['rho'], global_model_data['epsilon'])",
"adagrad": "adagrad(global_model_data['learningRate'], global_model_data['initialAccumulatorValue'])",
"adam": "adam(global_model_data['learningRate'], global_model_data['beta1'], global_model_data['beta2'], global_model_data['epsilon'])",
"adamax": "adamax(global_model_data['learningRate'], global_model_data['beta1'], global_model_data['beta2'], global_model_data['epsilon'], global_model_data['decay'])",
"rmsprop": "rmsprop(global_model_data['learningRate'], global_model_data['decay'], global_model_data['momentum'], global_model_data['epsilon'], global_model_data['centered'])",
"sgd": "sgd(global_model_data['learningRate'])"
};
if(!optimizer_name_only) {
global_model_data["optimizer"] = tidy(() => { return eval("tf.train." + optimizer_constructors[global_model_data["optimizer"]]); });
}
return global_model_data;
}
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
async function get_fit_data () {
var epochs = get_epochs();
var batchSize = get_batch_size();
var validationSplit = parse_int($("#validationSplit").val()) / 100;
var callbacks = {};
callbacks["onTrainBegin"] = async function () {
confusion_matrix_and_grid_cache = {};
current_epoch = 0;
this_training_start_time = Date.now();
$(".training_performance_tabs").show();
await show_tab_label("training_tab_label", jump_to_interesting_tab());
$("#network_has_seen_msg").hide();
await visualize_train();
await confusion_matrix_to_page(); // async not possible
confusion_matrix_and_grid_cache = {};
};
callbacks["onBatchBegin"] = async function () {
confusion_matrix_and_grid_cache = {};
if(!started_training) {
model.stopTraining = true;
}
if(!is_hidden_or_has_hidden_parent($("#math_tab"))) {
await write_model_to_latex_to_page();
}
confusion_matrix_and_grid_cache = {};
};
callbacks["onEpochBegin"] = async function () {
confusion_matrix_and_grid_cache = {};
current_epoch++;
var max_number_epochs = get_epochs();
var current_time = Date.now();
var epoch_time = (current_time - this_training_start_time) / current_epoch;
var epochs_left = max_number_epochs - current_epoch;
var seconds_left = parse_int(Math.ceil((epochs_left * epoch_time) / 1000) / 5) * 5;
var time_estimate = human_readable_time(seconds_left);
$("#training_progress_bar").show();
set_document_title("[" + current_epoch + "/" + max_number_epochs + ", " + time_estimate + "] asanAI");
var percentage = parse_int((current_epoch / max_number_epochs) * 100);
$("#training_progressbar>div").css("width", percentage + "%");
confusion_matrix_and_grid_cache = {};
};
callbacks["onBatchEnd"] = async function (batch, logs) {
confusion_matrix_and_grid_cache = {};
delete logs["batch"];
delete logs["size"];
var batchNr = 1;
var loss = logs["loss"];
if(training_logs_batch["loss"]["x"].length) {
batchNr = Math.max(...training_logs_batch["loss"]["x"]) + 1;
}
training_logs_batch["loss"]["x"].push(batchNr);
training_logs_batch["loss"]["y"].push(loss);
if(!last_batch_time) {
last_batch_time = +new Date();
} else {
var current_time = +new Date();
time_per_batch["time"]["x"].push(batchNr);
time_per_batch["time"]["y"].push((current_time - last_batch_time) / 1000);
last_batch_time = current_time;
}
var this_plot_data = [training_logs_batch["loss"]];
$("#plotly_batch_history").parent().show();
$("#plotly_time_per_batch").parent().show();
if(!last_batch_plot_time || (Date.now() - last_batch_plot_time) > (parse_int($("#min_time_between_batch_plots").val()) * 1000)) { // Only plot every min_time_between_batch_plots seconds
if(batchNr == 1) {
Plotly.newPlot("plotly_batch_history", this_plot_data, get_plotly_layout(language[lang]["batches"]));
Plotly.newPlot("plotly_time_per_batch", [time_per_batch["time"]], get_plotly_layout(language[lang]["time_per_batch"]));
} else {
Plotly.update("plotly_batch_history", this_plot_data, get_plotly_layout(language[lang]["batches"]));
Plotly.update("plotly_time_per_batch", [time_per_batch["time"]], get_plotly_layout(language[lang]["time_per_batch"]));
}
last_batch_plot_time = Date.now();
}
if(!is_hidden_or_has_hidden_parent($("#predict_tab"))) {
if($("#predict_own_data").val()) {
await predict($("#predict_own_data").val());
}
await show_prediction(0, 1);
if(await input_shape_is_image()) {
await repredict();
}
}
confusion_matrix_and_grid_cache = {};
await restart_fcnn();
};
callbacks["onEpochEnd"] = async function (batch, logs) {
confusion_matrix_and_grid_cache = {};
delete logs["epoch"];
delete logs["size"];
var epochNr = 1;
var loss = logs["loss"];
if(training_logs_epoch["loss"]["x"].length) {
epochNr = Math.max(...training_logs_epoch["loss"]["x"]) + 1;
}
training_logs_epoch["loss"]["x"].push(epochNr);
training_logs_epoch["loss"]["y"].push(loss);
var other_key_name = "val_loss";
var this_plot_data = [training_logs_epoch["loss"]];
if(Object.keys(logs).includes(other_key_name)) {
if(epochNr == 1 || !Object.keys(training_logs_epoch).includes(other_key_name)) {
training_logs_epoch[other_key_name] = {
"x": [],
"y": [],
"type": get_scatter_type(),
"mode": get_plotly_layout(),
"name": "Loss"
};
}
loss = logs[other_key_name];
training_logs_epoch[other_key_name]["x"].push(epochNr);
training_logs_epoch[other_key_name]["y"].push(loss);
training_logs_epoch[other_key_name]["mode"] = get_plotly_type();
training_logs_epoch[other_key_name]["name"] = other_key_name;
this_plot_data.push(training_logs_epoch[other_key_name]);
}
$("#plotly_epoch_history").parent().show();
$("#plotly_epoch_history").show();
if(epochNr == 1) {
Plotly.newPlot("plotly_epoch_history", this_plot_data, get_plotly_layout(language[lang]["epochs"]));
} else {
Plotly.update("plotly_epoch_history", this_plot_data, get_plotly_layout(language[lang]["epochs"]));
}
await visualize_train();
if(training_logs_batch && "loss" in training_logs_batch) {
var this_plot_data = [training_logs_batch["loss"]];
Plotly.update("plotly_batch_history", this_plot_data, get_plotly_layout(language[lang]["batches"]));
}
if(time_per_batch && "time" in time_per_batch) {
Plotly.update("plotly_time_per_batch", [time_per_batch["time"]], get_plotly_layout(language[lang]["time_per_batch"]));
}
last_batch_plot_time = false;
if(training_logs_epoch["loss"].x.length >= 2) {
var vl = Object.keys(training_logs_epoch).includes("val_loss") ? training_logs_epoch["val_loss"].y : null;
var th = 18;
var plotCanvas = create_tiny_plot(training_logs_epoch["loss"].x, training_logs_epoch["loss"].y, vl, th * 2, parse_int(0.9 * th));
$("#tiny_graph").html("");
$("#tiny_graph").append(plotCanvas).show();
} else {
$("#tiny_graph").html("").hide();
}
$("#network_has_seen_msg").show();
confusion_matrix_to_page(); // async not possible
confusion_matrix_and_grid_cache = {};
};
callbacks["onTrainEnd"] = async function () {
confusion_matrix_and_grid_cache = {};
favicon_default();
await write_model_to_latex_to_page();
set_document_title(original_title);
await restart_fcnn();
$("#tiny_graph").hide();
$("#network_has_seen_msg").hide();
confusion_matrix_to_page(); // async not possible
await reset_data();
confusion_matrix_and_grid_cache = {};
};
var fit_data = {
validationSplit: validationSplit,
batchSize: batchSize,
epochs: epochs,
shuffle: $("#shuffle_before_each_epoch").is(":checked"),
verbose: 0,
callbacks: callbacks,
yieldEvery: "batch"
};
traindebug("fit_data:");
traindebug(fit_data);
return fit_data;
}
function create_tiny_plot(x, y, y_val, w, h) {
try {
// Check if x and y arrays have the same size
if (x.length !== y.length) {
throw new Error("x and y arrays must have the same size");
}
if((y_val && y_val.length != x.length) || !y_val) {
y_val = [];
}
// Create a canvas element
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext("2d");
// Define plot parameters
// Calculate the x-axis scaling factor to fit the entire width
const xScale = (w - 2) / (x.length - 1);
// Find the range of y values
const minY = Math.min(Math.min(...y), Math.min(...y_val));
const maxY = Math.max(Math.max(...y), Math.max(...y_val));
// Calculate the y-axis scaling factor
const yScale = (h - 2) / (maxY - minY);
// Plot the training loss (in blue)
ctx.beginPath();
ctx.strokeStyle = "blue";
ctx.lineWidth = 2;
ctx.beginPath();
for (let i = 0; i < x.length; i++) {
const xCoord = i * xScale;
const yCoord = h - (y[i] - minY) * yScale;
//log("x, y:", xCoord, yCoord);
//log("h, y, y[i], minY, yScale:", h, y, y[i], minY, yScale, "<<<<<<");
if (i === 0) {
ctx.moveTo(xCoord, yCoord);
} else {
ctx.lineTo(xCoord, yCoord);
}
}
ctx.stroke();
if(y_val.length) {
ctx.beginPath();
ctx.strokeStyle = "orange";
for (let i = 0; i < y_val.length; i++) {
const xCoord = i * xScale;
const yCoord = h - (y_val[i] - minY) * yScale;
if (i === 0) {
ctx.moveTo(xCoord, yCoord);
} else {
ctx.lineTo(xCoord, yCoord);
}
}
ctx.stroke();
}
return canvas; // Return the canvas element
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
assert(false, e);
}
}
//var pc = create_tiny_plot([1,2,3,4], [1,2,3,4], [5,6,7,8], 20, 20); $("#tiny_graph").html(""); $("#tiny_graph").append(pc).show();
function _set_apply_to_original_apply () {
assert(Object.keys(model).includes("layers"), "model does not include layers");
for (var i = 0; i < model.layers.length; i++) {
if("original_apply" in model.layers[i]) {
try {
eval("model.layers[" + i + "].apply = model.layers[" + i + "].original_apply;\n");
} catch (e) {
err(e);
console.trace();
}
}
}
}
async function _get_xs_and_ys (recursive=0) {
var xs_and_ys = false;
try {
var error_string = "";
write_model_summary_wait();
await disable_everything();
l(language[lang]["getting_data"] + "...");
xs_and_ys = await get_xs_and_ys();
await show_tab_label("training_tab_label", jump_to_interesting_tab());
l(language[lang]["got_data"]);
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
if(("" + e).includes("n is undefined") && recursive == 0) {
wrn("[_get_xs_and_ys] Error '" + e + "'. Trying to get xs and ys again...");
return await _get_xs_and_ys(recursive + 1);
} else {
var explanation = explain_error_msg("" + e);
if(explanation) {
explanation = "<br><br>" + explain_error_msg(e.toString());
} else {
explanation = "";
}
await send_bug_report();
Swal.fire(
"Error while training",
e.toString() + explanation,
"warning"
);
header("ERROR");
log(e);
header("ERROR END");
console.trace();
}
favicon_default();
await write_descriptions();
$(".train_neural_network_button").html("<span class='TRANSLATEME_start_training'></span>").removeClass("stop_training").addClass("start_training");
await update_translations();
started_training = false;
return false;
}
return xs_and_ys;
}
async function _show_or_hide_simple_visualization (fit_data, xs_and_ys) {
try {
var x_shape_is_ok = xs_and_ys["x"].shape.length == 2 && xs_and_ys["x"].shape[1] == 1;
var y_shape_is_ok = xs_and_ys["y"].shape.length == 2 && xs_and_ys["y"].shape[1] == 1;
var model_shape_is_ok = model.input.shape.length == 2 && model.input.shape[1] == 1;
if(
x_shape_is_ok &&
y_shape_is_ok &&
model &&
model_shape_is_ok
) {
if(!model) {
wrn("[_show_or_hide_simple_visualization] Model not found. Not showing simple visualization");
old_onEpochEnd = undefined;
$("#simplest_training_data_visualization").html("").hide();
return;
}
old_onEpochEnd = fit_data["callbacks"]["onBatchEnd"];
var x_data_json = JSON.stringify(array_sync(xs_and_ys["x"]));
var y_data_json = JSON.stringify(array_sync(xs_and_ys["y"]));
var new_on_batch_end_callback = await get_live_tracking_on_batch_end(
"model",
parse_int($("#epochs").val()),
x_data_json,
y_data_json,
false,
"simplest_training_data_visualization"
);
//log(new_on_batch_end_callback);
if(new_on_batch_end_callback) {
fit_data["callbacks"]["onBatchEnd"] = new_on_batch_end_callback;
//log("tried installing new callbacks in fit_data:", fit_data);
$("#simplest_training_data_visualization").show();
} else {
log(language[lang]["could_not_install_new_callback"]);
}
} else {
var shown_warnings = false;
if(!model) {
dbg(language[lang]["model_is_not_defined"]);
shown_warnings = true;
}
if(!x_shape_is_ok) {
dbg(`${language[lang]["x_shape_is_wrong_for_simple_visualization"]}: [${xs_and_ys["x"].shape.join(", ")}]`);
shown_warnings = true;
}
if(!y_shape_is_ok) {
dbg(`${language[lang]["y_shape_is_wrong_for_simple_visualization"]}: [${xs_and_ys["y"].shape.join(", ")}]`);
shown_warnings = true;
}
if(!model_shape_is_ok) {
dbg(`${language[lang]["model_shape_is_wrong_for_simple_visualization"]}: ${model_shape_to_string(model.input.shape)}`);
shown_warnings = true;
}
if (!shown_warnings) {
dbg(language[lang]["unknown_reason_for_not_displaying_simple_visualization"]);
}
old_onEpochEnd = undefined;
$("#simplest_training_data_visualization").html("").hide();
}
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
assert(false, e);
}
}
function model_shape_to_string (model_shape) {
try {
if (!Array.isArray(model_shape)) {
throw new Error("Input is not an array.");
}
const result = model_shape.map((element) => {
return element === null ? "null" : element;
});
return "[" + result.join(", ") + "]";
} catch (error) {
console.error("Error:", error.message);
// Handle the error or rethrow it based on your requirements
}
}
//console.log(convertNullToString([1, null, 3])); // Ausgabe: '[1, "null", 3]'
//console.log(convertNullToString([1, 2, 3])); // Ausgabe: '[1, 2, 3]'
//console.log(convertNullToString([null, 1, 2, 3, 4, 5])); // Ausgabe: '["null", 1, 2, 3, 4, 5]'
function _clear_plotly_epoch_history () {
$("#plotly_epoch_history").parent().hide();
$("#plotly_epoch_history").html("");
}
async function _get_fit_data (xs_and_ys) {
var fit_data = true;
try {
add_layer_debuggers();
fit_data = await get_fit_data();
await _show_or_hide_simple_visualization(fit_data, xs_and_ys);
await show_tab_label("training_tab_label", jump_to_interesting_tab());
} catch (e) {
await write_error_and_reset(e);
fit_data = false;
}
return fit_data;
}
async function repair_output_shape (tries_classification_but_receives_other=0) {
if(!model) {
model = await create_model();
await compile_model();
}
try {
var last_layer_output_shape = model.layers[model.layers.length - 1].output.shape;
if(last_layer_output_shape.length == 2) {
var num_categories = labels.length;
if(!num_categories) {
return false;
}
if(last_layer_output_shape[1] != num_categories) {
$($(".glass_box")[model.layers.length - 1]).find(".units").val(labels.length);
await updated_page();
log(language[lang]["not_rerunning_run_neural_network"]);
return true;
} else {
return false;
}
} else {
if(tries_classification_but_receives_other) {
var ll = labels.length;
show_overlay(language[lang]["fixing_output_shape"]);
if(labels && ll) {
is_repairing_output_shape = true;
var change_to_beginner = 0;
if(mode == "beginner") {
l(language[lang]["temporarily_using_expert_mode"] + "...");
change_to_beginner = 1;
mode = "expert";
}
await (async () => {
try {
function get_last_layer (minus=1) {
void(0); dbg(`get_last_layer(${minus})`);
return $(".layer_type").length - minus;
}
async function change_layer_to (nr, to) {
void(0); dbg(`change_layer_to(${nr}, ${to})`);
var layer_type = $(".layer_type")[nr];
var $layer_type = $(layer_type);
var index = 0;
if(to == "dense") {
index = 0;
} else if(to == "flatten") {
index = 1;
} else {
throw new Error("unknown to-value:" + to);
}
dbg(language[lang]["changing_val_to"] + " " + to);
$layer_type.val(to);
dbg(language[lang]["changing_selectedIndex"] + " " + index);
$layer_type.prop("selectedIndex", index);
void(0); dbg("triggering $layer_type:", $layer_type);
$layer_type.trigger("change");
dbg(sprintf(language[lang]["start_waiting_for_x_becoming_equal_to_y"], $layer_type.val(), to));
while ($layer_type.val() != to) {
dbg(sprintf(language[lang]["currently_waiting_for_n_layer_m_becoming_equal_to_a"], $layer_type.val(), nr, to));
await delay(100);
}
await delay(500);
}
async function duplicate_last_layer () {
dbg(language[lang]["adding_layer"]);
var $last_layer = $(".add_layer")[get_last_layer()];
dbg(language[lang]["awaiting_disable_invalid_layers_event"]); // await
enable_all_layer_types();
var start_layers = model.layers.length;
dbg(language[lang]["clicking_on_this_item_for_layer_duplication"], $last_layer);
$last_layer.click();
while (model.layers.length - (start_layers) > 0) {
dbg(sprintf(language[lang]["waiting_until_model_layers_length_m_minus_start_layers_n_is_greater_than_zero"], model.layers.length, start_layers));
await delay(200);
}
await delay(1000);
if(mode == "beginner") {
await disable_invalid_layers_event(new Event("duplicate_last_layer"), $last_layer);
}
}
async function set_activation_to (nr, val) {
void(0), dbg(`set_activation_to(${nr}, ${val})`);
$($(".layer_setting")[nr]).find(".activation").val(val).trigger("change");
while ($($(".layer_setting")[nr]).find(".activation").val() != val) {
await delay(100);
}
await delay(500);
}
async function set_dense_layer_units(nr, units) {
dbg(sprintf(language[lang]["setting_the_units_of_layer_n_to_m"], nr, units));
var $units = $($(".layer_setting")[nr]).find(".units");
$units.val(units);
while (ll != $units.val()) {
dbg(`${language[lang]["waiting_for_set_dense_layer_units"]}(${nr}, ${units})`);
await delay(100);
}
await delay(500);
}
await duplicate_last_layer();
await change_layer_to(get_last_layer() - 1, "flatten");
await duplicate_last_layer();
await change_layer_to(get_last_layer(), "dense");
await set_dense_layer_units(get_last_layer(), ll);
await set_activation_to(get_last_layer(), "softmax");
$(".overlay").remove();
$("#start_training").click();
} catch (e) {
$(".overlay").remove();
$("#start_training").click();
throw new Error(e);
}
})();
if(change_to_beginner) {
mode = "beginner";
}
is_repairing_output_shape = false;
return true;
} else {
return false;
}
}
}
} catch (e) {
if(Object.keys(e).includes("message")) {
e = e.message;
}
if(("" + e).includes("model.layers is undefined")) {
wrn("[repair_output_shape] model.layers is undefined");
} else {
throw new Error(e);
}
}
return false;
}
async function run_neural_network (recursive=0) {
await wait_for_updated_page(2);
if(!model) {
err(`[run_neural_network] ${language[lang]["no_model_defined"]}`);
return;
}
if(model.layers.length == 0) {
err(`[run_neural_network] ${language[lang]["no_layers"]}`);
return;
}
await clean_gui();
$(".train_neural_network_button").html("<span class='TRANSLATEME_stop_training'></span>").removeClass("start_training").addClass("stop_training");
await update_translations();
_set_apply_to_original_apply();
var xs_and_ys = await _get_xs_and_ys();
if(!xs_and_ys) {
err(`[run_neural_network] ${language[lang]["could_not_get_xs_and_xy"]}`);
return;
}
var repaired = false;
if(started_training) {
$(".overlay").remove();
var inputShape = await set_input_shape("[" + xs_and_ys["x"].shape.slice(1).join(", ") + "]");
$("#training_content").clone().prepend("<hr>").appendTo("#training_tab");
_clear_plotly_epoch_history();
if(!model) {
model = await create_model();
await compile_model();
}
var fit_data = await _get_fit_data(xs_and_ys);
await show_tab_label("training_tab_label", jump_to_interesting_tab());
try {
l(language[lang]["compiling_model"]);
await compile_model();
l(language[lang]["started_training"]);
h = await model.fit(xs_and_ys["x"], xs_and_ys["y"], fit_data);
l(language[lang]["finished_training"]);
await nextFrame();
assert(typeof(h) == "object", "history object is not of type object");
model_is_trained = true;
$("#predictcontainer").show();
$("#predict_error").hide().html("");
} catch (e) {
log(e);
if(("" + e).includes("is already disposed")) {
err("[run_neural_network] Model was already disposed, this may be the case when, during the training, the model is re-created and something is tried to be predicted. USUALLY, not always, this is a harmless error.");
// input expected a batch of elements where each example has shape [2] (i.e.,tensor shape [*,2]) but the input received an input with 5 examples, each with shape [3] (tensor shape [5,3])
} else if (("" + e).includes("input expected a batch of elements where each example has shape")) {
err("[run_neural_network] Error: " + e + ". This may mean that you got the file from CSV mode but have not waited long enough to parse the file.");
} else if (("" + e).includes("n is undefined")) {
while (!model) {
dbg("[run_neural_network] Waiting for model...");
delay(500);
}
wrn("[run_neural_network] Error: " + e + ". This may mean the model was not yet compiled");
if(!recursive) {