-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1420 lines (1232 loc) · 63.9 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
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
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis-network.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<title>IA1 - Proyecto 2</title>
</head>
<body class="bg-gray-100 p-10 font-sans">
<div class="max-w-4xl mx-auto p-8 bg-white shadow-md rounded-lg">
<h1 class="text-4xl font-bold text-center text-blue-600 mb-8">Proyecto 2 - Implementacion de libreria tytus.js
</h1>
<h2 class="text-2xl font-semibold text-gray-700 mt-6 mb-4">Paso 1: Carga del dataset</h2>
<p class="text-gray-600 mb-4">Archivo CSV que se utilizará para entrenar y validar los algoritmos de
inteligencia artificial</p>
<input type="file" id="csvFile" accept=".csv">
<br>
<h2 class="text-2xl font-semibold text-gray-700 mt-6 mb-4">Paso 2: Selección del modelo de inteligencia
artificial</h2>
<p class="text-gray-600 mb-4">Elección del algoritmo de inteligencia artificial que se hará uso, se encuentran
disponibles los principales
que
proporciona la libreria tytus.js:</p>
<div class="overflow-x-auto">
<table class="min-w-full bg-white border border-gray-200 rounded-lg">
<thead>
<tr>
<th class="px-6 py-3 text-left text-gray-700 uppercase font-semibold">Modelo de IA</th>
<th class="px-6 py-3 text-left text-gray-700 uppercase font-semibold">Propósito de uso</th>
</tr>
</thead>
<tbody>
<tr class="border-t">
<td class="px-6 py-4 text-gray-600">Linear Regression</td>
<td class="px-6 py-4 text-gray-600">Identificación de <b>tendencias</b></td>
</tr>
<tr class="border-t">
<td class="px-6 py-4 text-gray-600">Polynomial Regression</td>
<td class="px-6 py-4 text-gray-600">Identificación de <b>tendencias</b></td>
</tr>
<tr class="border-t">
<td class="px-6 py-4 text-gray-600">Naive Bayes</td>
<td class="px-6 py-4 text-gray-600">Realización de <b>predicciones</b></td>
</tr>
<tr class="border-t">
<td class="px-6 py-4 text-gray-600">Neural Networks</td>
<td class="px-6 py-4 text-gray-600">Realización de <b>predicciones</b></td>
</tr>
<tr class="border-t">
<td class="px-6 py-4 text-gray-600">Decision Trees</td>
<td class="px-6 py-4 text-gray-600">Organización de la información mediante <b>patrones</b></td>
</tr>
<tr class="border-t">
<td class="px-6 py-4 text-gray-600">K-means</td>
<td class="px-6 py-4 text-gray-600">Organización de la información mediante <b>patrones</b></td>
</tr>
</tbody>
</table>
</div>
<br>
<div class="flex flex-row">
<label for="model">Modelo a utilizar: </label>
<select id="model" onchange="modelSelection()" class="p-2 border border-gray-300 rounded-md w-full">
<option value="empty">---</option>
<option value="linear">Linear Regression</option>
<option value="polynomial">Polynomial Regression</option>
<option value="bayes">Naive Bayes</option>
<option value="neural">Neural Networks</option>
<option value="decision">Decision Trees</option>
<option value="kmeans">K-means</option>
</select>
</div>
<h2 class="text-2xl font-semibold text-gray-700 mt-6 mb-4">Paso 3: Parametrización del modelo</h2>
<p class="text-gray-600 mb-4">Campos que se necesitan llenar para parametrizar el comportamiento del modelo</p>
<h3 class="text-xl font-semibold text-gray-700 mb-2">- Parametros generales</h3>
<div>
<p class="text-gray-600 mb-2">Porcentaje de los datos que será utilizada para el entrenamiento y porcentaje
que será utilizada para las
pruebas de las predicciones</p>
<datalist id="marks">
<option value="0" label="0%"></option>
<option value="10"></option>
<option value="20"></option>
<option value="30"></option>
<option value="40"></option>
<option value="50" label="50%"></option>
<option value="60"></option>
<option value="70"></option>
<option value="80"></option>
<option value="90"></option>
<option value="100" label="100%"></option>
</datalist>
<div class="flex flex-row">
<div class="flex flex-col justify-center mr-4">
<label for="data-percent">Train data</label>
<b><output id="train-percent" for="range"></output>%</b>
</div>
<input type="range" list="marks" value="80" class="w-full" />
<div class="flex flex-col justify-center ml-4">
<label for="data-percent">Test data</label>
<b><output id="test-percent" for="range"></output>%</b>
</div>
</div>
</div>
<br>
<h3 class="text-xl font-semibold text-gray-700 mb-2">- Parametros especificos del modelo</h3>
<div id="error-parameters" class="text-rose-600">
<p>Porfavor cargar un archivo CSV</p>
</div>
<div id="regression-parameters">
<div class="mb-4">
<label for="x">Columna de la variable independiente (X)</label>
<select id="x" class="p-2 border border-gray-300 rounded-md">
</select>
</div>
<div>
<label for="y">Columna de la variable dependiente (Y)</label>
<select id="y" class="p-2 border border-gray-300 rounded-md">
</select>
</div>
</div>
<div id="decision-parameters">
<p class="text-gray-600 mb-2">Es necesario indicar cuales columnas del CSV son las que almacenan los
atributos que serán tomados en
cuenta
para entrenar el algoritmo</p>
<div class="flex flex-row items-center gap-2">
<label for="decision-options" class="w-96">Seleccione una columna</label>
<select id="decision-options" class="p-2 border border-gray-300 rounded-md w-full">
</select>
<button onclick="addAtributeToTable('decision')"
class="bg-gray-500 text-white font-semibold py-2 px-4 rounded hover:bg-blue-600">Agregar
columna</button>
<button onclick="addDefaultValuesToTable('decision')"
class="bg-gray-500 text-white font-semibold py-2 px-4 rounded hover:bg-blue-600 w-72">Agregar
valores por defecto</button>
</div>
<br>
<table id="decision-table" border="block" class="min-w-full bg-white border border-gray-200 rounded-lg">
<thead>
<tr>
<th>Atributos del dataset</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div id="bayes-parameters">
<p class="text-gray-600 mb-4">Es necesario indicar cuales columnas del CSV son las que almacenan los
atributos que serán tomados en
cuenta
para entrenar el algoritmo</p>
<div class="grid grid-cols-2 gap-8">
<div>
<div class="flex flex-row">
<label for="bayes-options">Seleccione una columna</label>
<select id="bayes-options" class="p-2 border border-gray-300 rounded-md w-full">
</select>
</div>
<br>
<div class="flex justify-center gap-1">
<button onclick="addAtributeToTable('bayes')"
class="bg-gray-500 text-white font-semibold py-2 px-4 rounded hover:bg-blue-600">Agregar
columna</button>
<button onclick="addDefaultValuesToTable('bayes')"
class="bg-gray-500 text-white font-semibold py-2 px-4 rounded hover:bg-blue-600">Agregar
valores
por
defecto</button>
</div>
<br>
<table id="bayes-table" class="min-w-full bg-white border border-gray-200 rounded-lg">
<thead>
<tr>
<th class="px-6 py-3 text-left text-gray-700 uppercase font-semibold">Atributos a
utilizar
del dataset</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div>
<div class="flex flex-row">
<p>¿Qué variable predecir?</p>
<select id="bayes-variable" class="p-2 border border-gray-300 rounded-md w-full"></select>
</div>
<br>
<p>¿Bajo de qué condiciones se desea predecir la variable?</p>
<table id="bayes-variable-values" class="min-w-full bg-white border border-gray-200 rounded-lg">
<thead>
<tr>
<th class="px-6 py-3 text-left text-gray-700 uppercase font-semibold">Variable</th>
<th class="px-6 py-3 text-left text-gray-700 uppercase font-semibold">Valor</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<div id="neural-parameters">
<div class="grid grid-cols-2 gap-8 items-center">
<div class="flex flex-col">
<label for="neural-prediction">¿Que tipo de prediccion desea realizar?</label>
<select id="neural-prediction" class="p-2 border border-gray-300 rounded-md w-full">
<option id="higher">¿Cual elemento es el mayor?</option>
<option id="lower">¿Cual elemento es el menor?</option>
</select>
</div>
<div class="flex flex-col gap-2">
<div class="flex flex-row">
<label for="neural-A" class="text-center">Elemento A:</label>
<input id="neural-A" type="number" class="p-2 border border-gray-300 rounded-md w-full mx-4" />
</div>
<div class="flex flex-row">
<label for="neural-B" class="text-center">Elemento B:</label>
<input id="neural-B" type="number" class="p-2 border border-gray-300 rounded-md w-full mx-4" />
</div>
</div>
</div>
</div>
<div id="kmeans-parameters">
<p class="text-gray-600 mb-4">Es necesario indicar cuales columnas del CSV son las que almacenan los
atributos que serán tomados en
cuenta
para entrenar el algoritmo</p>
<div class="grid grid-cols-1 gap-2">
<div class="flex flex-row items-center">
<label for="kmeans-x-options" class="w-96">Referencia en el eje X del punto</label>
<select id="kmeans-x-options" class="p-2 border border-gray-300 rounded-md w-full">
</select>
</div>
<div class="flex flex-row items-center">
<label for="kmeans-y-options" class="w-96">Referencia en el eje Y del punto</label>
<select id="kmeans-y-options" class="p-2 border border-gray-300 rounded-md w-full">
</select>
</div>
<div class="flex flex-row items-center">
<label for="kmeans-y-options" class="w-96">Cantidad de centroides a calcular</label>
<input id="kmeans-centroides" type="number" class="p-2 border border-gray-300 rounded-md w-full" />
</div>
</div>
</div>
<div id="knearest-parameters">
</div>
<h2 class="text-2xl font-semibold text-gray-700 mt-6 mb-4">Paso 4: Uso del modelo</h2>
<p class="text-gray-600 mb-2">Acciones disponibles para usar el modelo según la configuración previamente
establecida
</p>
<p id="aclaracion-paso4" class="text-gray-600 mb-2"><b>NOTA:</b> La implementacion de tytus.js del modelo de IA
seleccionado no permite el entrenamiento manual, esto lo realiza internamente el modelo al realizar una
proyeccion.</p>
<div class="flex flex-row gap-2">
<button onclick="trainModel()"
class="bg-blue-500 text-white font-semibold py-2 px-4 rounded hover:bg-blue-600"
id="train-button">Entrenar</button>
<button onclick="predictModel()"
class="bg-green-500 text-white font-semibold py-2 px-4 rounded hover:bg-green-600">Predecir</button>
<button onclick="showResultChart()"
class="bg-purple-500 text-white font-semibold py-2 px-4 rounded hover:bg-purple-600"
id="show-graphics-button">Mostrar
graficas</button>
</div>
<h2 class="text-2xl font-semibold text-gray-700 mt-6 mb-4">Area de resultados</h2>
<p id="result" class="text-ellipsis overflow-hidden"></p>
<div id="graphics" style="display: none;">
<h2 class="text-2xl font-semibold text-gray-700 mt-6 mb-4">Area de graficas</h2>
<div id="training-charts">
<label for="trained-chart">Datos utilizados para el entrenamiento</label>
<div id="trained-chart" style="width: 100%; height: 500px;"></div>
</div>
<div id="prediction-charts">
<label for="predicted-chart">Datos predecidos por el modelo</label>
<div id="predicted-chart" style="width: 100%; height: 500px;"></div>
</div>
<div id="tree-charts" style="display: none;">
<label for="tree">Arbol de decision generado</label>
<div style="width: 100%; height: 500px; border: 2px dashed red; border-radius: 10px;" id="tree"></div>
</div>
</div>
<div id="canvas" style="display: none;">
<h2 class="text-2xl font-semibold text-gray-700 mt-6 mb-4">Area de canvas</h2>
<canvas id="kmeans-canva" width="600" height="600"></canvas>
</div>
</div>
<div style="display: none;">
<div id="salida"></div>
<div id="salida1"></div>
<div id="salida2"></div>
<div id="salida3"></div>
<div id="salida4"></div>
</div>
<script type="text/javascript" src="./tytus.js"></script>
<script>
let csvContent = "";
let csvController;
let linearRegressionModel;
let twoGradePolynomialRegression;
let threeGradePolynomialRegression;
let fourGradePolynomialRegression;
let decisionTreeModel;
let naiveBayesModel;
let neuralNetworkModel;
let g8MeansModel;
function trainModel() {
const model = document.getElementById("model").value;
const trainPercent = document.getElementById("train-percent").value;
switch (model) {
case "linear":
{
const xColumn = document.getElementById("x").value;
const yColumn = document.getElementById("y").value;
const xData = csvController.getNumberDataFromColumn(xColumn);
const yData = csvController.getNumberDataFromColumn(yColumn);
const maxTrainingIndex = Math.floor(xData.length * trainPercent / 100);
const trainingXData = xData.slice(0, maxTrainingIndex);
const trainingYData = yData.slice(0, maxTrainingIndex);
linearRegressionModel = new LinearRegressionAdapter();
linearRegressionModel.train(trainingXData, trainingYData);
document.getElementById("result").innerText =
"Modelo de tendencia lineal entrenado con los siguientes datos:\n"
+ "--- X: [" + trainingXData + "]\n"
+ "--- Y: [" + trainingYData + "]";
}
break;
case "polynomial":
{
const xColumn = document.getElementById("x").value;
const yColumn = document.getElementById("y").value;
const xData = csvController.getNumberDataFromColumn(xColumn);
const yData = csvController.getNumberDataFromColumn(yColumn);
const maxTrainingIndex = Math.floor(xData.length * trainPercent / 100);
const trainingXData = xData.slice(0, maxTrainingIndex);
const trainingYData = yData.slice(0, maxTrainingIndex);
twoGradePolynomialRegression = new PolynomialRegressionAdapter();
threeGradePolynomialRegression = new PolynomialRegressionAdapter();
fourGradePolynomialRegression = new PolynomialRegressionAdapter();
twoGradePolynomialRegression.trainTwoGradeRegression(trainingXData, trainingYData);
threeGradePolynomialRegression.trainThreeGradeRegression(trainingXData, trainingYData);
fourGradePolynomialRegression.trainFourGradeRegression(trainingXData, trainingYData);
document.getElementById("result").innerText =
"Modelo entrenado con tendencias en base a polinomios de 2do, 3er y 4to grado con los siguientes datos:\n"
+ "--- X: [" + trainingXData + "]\n"
+ "--- Y: [" + trainingYData + "]";
}
break;
case "decision":
{
const celdas = document.getElementById("decision-table").getElementsByTagName("tbody")[0].getElementsByTagName("td");
let csvColumns = [];
let csvColumnNames = []
for (let i = 0; i < celdas.length; i++) {
const csvColumn = csvController.getStringDataFromColumn(celdas[i].textContent);
const maxTrainingIndex = Math.floor(csvColumn.length * trainPercent / 100);
const filteredCsvColumnValues = csvColumn.slice(0, maxTrainingIndex);
csvColumns.push(filteredCsvColumnValues);
csvColumnNames.push(celdas[i].textContent);
}
let trainingCsvData = [];
for (let i = 0; i < csvColumns.length; i++) {
trainingCsvData.push(csvColumnNames[i]);
trainingCsvData.push(csvColumns[i]);
}
let trainingDataSet = joinNArrays(...trainingCsvData)
decisionTreeModel = new DecisionTreeID3Adapter(trainingDataSet);
decisionTreeModel.train();
let txt = "[\n";
for (let i = 0; i < trainingDataSet.length; i++) {
txt += " [ " + trainingDataSet[i] + "],\n"
}
txt += "]";
document.getElementById("result").innerText =
"Modelo entrenado con el siguiente dataset:\n" + txt;
}
break;
case "bayes":
{
alert('Este modelo no necesita fase de entrenamiento')
}
break;
case "neural":
{
alert('Este modelo no necesita fase de entrenamiento')
}
break;
case "kmeans":
{
alert('Este modelo no necesita fase de entrenamiento')
}
break;
case "knearest":
break;
}
}
function predictModel() {
const model = document.getElementById("model").value;
const trainPercent = document.getElementById("train-percent").value;
switch (model) {
case "linear":
{
const xColumn = document.getElementById("x").value;
const xData = csvController.getNumberDataFromColumn(xColumn);
if (!linearRegressionModel) {
alert('Modelo no entrenado previamente');
}
let maxTrainingIndex = Math.floor(xData.length * trainPercent / 100);
const predictXData = xData.slice(maxTrainingIndex);
const yPredicted = linearRegressionModel.predict(predictXData);
document.getElementById("result").innerText =
"Prediccion lineal realizada:\n"
+ "--- Variables de X proporcionadas: [" + predictXData + "]\n"
+ "--- Variables de Y predecidas: [" + yPredicted + "]";
}
break;
case "polynomial":
{
const xColumn = document.getElementById("x").value;
const xData = csvController.getNumberDataFromColumn(xColumn);
if (!twoGradePolynomialRegression) {
alert('Modelo no entrenado previamente');
}
let maxTrainingIndex = Math.floor(xData.length * trainPercent / 100);
const predictXData = xData.slice(maxTrainingIndex);
const yTwoPredicted = twoGradePolynomialRegression.predict(predictXData);
const yThreePredicted = threeGradePolynomialRegression.predict(predictXData);
const yFourPredicted = fourGradePolynomialRegression.predict(predictXData);
document.getElementById("result").innerText =
"Prediccion polinomial realizada:\n"
+ "--- Variables de X proporcionadas: [" + predictXData + "]\n"
+ "--- Variables de Y predecidas (2do grado): [" + yTwoPredicted + "]\n"
+ "--- Variables de Y predecidas (3er grado): [" + yThreePredicted + "]\n"
+ "--- Variables de Y predecidas (4to grado): [" + yFourPredicted + "]";
}
break;
case "decision":
{
if (!decisionTreeModel) {
alert('Modelo no entrenado previamente');
}
const celdas = document.getElementById("decision-table").getElementsByTagName("tbody")[0].getElementsByTagName("td");
let csvColumns = [];
let csvColumnNames = []
for (let i = 0; i < celdas.length; i++) {
const csvColumn = csvController.getStringDataFromColumn(celdas[i].textContent);
const maxTrainingIndex = Math.floor(csvColumn.length * trainPercent / 100);
const filteredCsvColumnValues = csvColumn.slice(maxTrainingIndex);
csvColumns.push(filteredCsvColumnValues);
csvColumnNames.push(celdas[i].textContent);
}
let predictingCsvData = [];
for (let i = 0; i < csvColumns.length; i++) {
predictingCsvData.push(csvColumnNames[i]);
predictingCsvData.push(csvColumns[i]);
}
let predictingDataSet = joinNArrays(...predictingCsvData)
let predictedResult = decisionTreeModel.predict(predictingDataSet);
let txtPredicting = "[\n";
for (let i = 0; i < predictingDataSet.length; i++) {
txtPredicting += " [ " + predictingDataSet[i] + "],\n"
}
txtPredicting += "]";
document.getElementById("result").innerText =
"Prediccion realizada:\n"
+ "Dataset enviado: " + txtPredicting + "\n"
+ "Respuesta:\n" + JSON.stringify(predictedResult);
}
break;
case "bayes":
{
const celdas = document.getElementById("bayes-table").getElementsByTagName("tbody")[0].getElementsByTagName("td");
let csvColumns = [];
let csvColumnNames = []
for (let i = 0; i < celdas.length; i++) {
const csvColumn = csvController.getStringDataFromColumn(celdas[i].textContent);
csvColumns.push(csvColumn);
csvColumnNames.push(celdas[i].textContent);
}
naiveBayesModel = new NaiveBayesAdapter();
for (let i = 0; i < csvColumns.length; i++) {
naiveBayesModel.insertCause(csvColumnNames[i], csvColumns[i]);
}
let predictionData = []
const modelVariables = document.getElementsByClassName('select-variables-bayes');
const variableValues = document.getElementsByClassName('select-values-bayes');
for (let i = 0; i < modelVariables.length; i++) {
const name = modelVariables[i].innerText;
const value = variableValues[i].value;
predictionData.push([name, value])
}
console.log(predictionData)
const predictionVariable = document.getElementById('bayes-variable').value;
let predictionResult = naiveBayesModel.predict(predictionVariable, predictionData);
console.log('Prediction result:');
console.log(predictionResult);
document.getElementById("result").innerHTML =
"El valor de <b>" + predictionVariable + "</b> sera <b>" + predictionResult[0] + "</b> con una probabilidad del <b>" + predictionResult[1] + "</b>";
}
break;
case "neural":
{
const action = document.getElementById('neural-prediction').value;
neuralNetworkModel = new NeuralNetworkAdapter();
switch (action) {
case '¿Cual elemento es el mayor?':
neuralNetworkModel.trainHigherElementsCase();
break;
case '¿Cual elemento es el menor?':
neuralNetworkModel.trainLowerElementsCase();
break;
}
const elementA = document.getElementById('neural-A').value;
const elementB = document.getElementById('neural-B').value;
const predictedResult = neuralNetworkModel.predict(elementA, elementB);
console.log(predictedResult)
switch (action) {
case '¿Cual elemento es el mayor?':
if (predictedResult[0] > 0.5) {
document.getElementById("result").innerHTML =
"El elemento A es el mayor con una probabilidad del <b>" + (predictedResult[0] * 100) + "% </b>";
} else {
document.getElementById("result").innerHTML =
"El elemento B es el mayor con una brobabilidad del <b>" + (predictedResult[1] * 100) + "% </b>";
}
break;
case '¿Cual elemento es el menor?':
if (predictedResult[0] > 0.5) {
document.getElementById("result").innerHTML =
"El elemento A es el menor con una probabilidad del <b>" + (predictedResult[0] * 100) + "% </b>";
} else {
document.getElementById("result").innerHTML =
"El elemento B es el menor con una brobabilidad del <b>" + (predictedResult[1] * 100) + "% </b>";
}
break;
}
}
break;
case "kmeans":
{
const xPoint = document.getElementById('kmeans-x-options').value;
const yPoint = document.getElementById('kmeans-y-options').value;
const xColumnValues = csvController.getNumberDataFromColumn(xPoint);
const yColumnValues = csvController.getNumberDataFromColumn(yPoint);
const trainingDataset = [];
for (let i = 0; i < xColumnValues.length; i++) {
trainingDataset.push([xColumnValues[i], yColumnValues[i]]);
}
const htmlCanvaElement = document.getElementById('kmeans-canva');
const centroidesNumber = document.getElementById('kmeans-centroides').value;
g8MeansModel = new G8_KmeansAdapter(htmlCanvaElement, trainingDataset, centroidesNumber);
const means = g8MeansModel.means();
let txtResult = '';
for (let i = 0; i < means.length; i++) {
txtResult += "---> Centroide cluster: [" + means[i] + "]\n"
}
document.getElementById("result").innerText =
"Dataset utilizado:\n" + JSON.stringify(trainingDataset) + "\n" +
"Numero de centroides a proyectar: " + centroidesNumber + "\n" +
"Resultado:\n" +
txtResult;
}
break;
case "knearest":
break;
}
}
function showResultChart() {
const graphicsArea = document.getElementById('graphics');
graphicsArea.style.display = 'block';
const model = document.getElementById("model").value;
const trainPercent = document.getElementById("train-percent").value;
switch (model) {
case "linear":
{
const xColumn = document.getElementById("x").value;
const yColumn = document.getElementById("y").value;
const xData = csvController.getNumberDataFromColumn(xColumn);
const yData = csvController.getNumberDataFromColumn(yColumn);
if (!linearRegressionModel) {
alert('Modelo no entrenado previamente');
}
if (!linearRegressionModel.predictXData || !linearRegressionModel.predictedYData) {
alert('No se ha realizado predicciones sobre el modelo previamente');
}
configureChart('trained-chart', 'X', xData, 'X,Y', yData)
configureChart('predicted-chart', 'X', linearRegressionModel.predictXData, 'X,Y', linearRegressionModel.predictedYData)
}
break;
case "polynomial":
{
const xColumn = document.getElementById("x").value;
const yColumn = document.getElementById("y").value;
const xData = csvController.getNumberDataFromColumn(xColumn);
const yData = csvController.getNumberDataFromColumn(yColumn);
if (!twoGradePolynomialRegression) {
alert('Modelo no entrenado previamente');
}
if (!twoGradePolynomialRegression.predictXData || !twoGradePolynomialRegression.predictedYData) {
alert('No se ha realizado predicciones sobre el modelo previamente');
}
configureChart('trained-chart', 'X', xData, 'Y', yData)
configureChart2('predicted-chart',
'X', twoGradePolynomialRegression.predictXData,
'2th Grade', twoGradePolynomialRegression.predictedYData,
'3th Grade', threeGradePolynomialRegression.predictedYData,
'4th Grade', fourGradePolynomialRegression.predictedYData
);
}
break;
case "decision":
{
if (!decisionTreeModel) {
alert('Modelo no entrenado previamente');
}
let dotStr = decisionTreeModel.generateDotString();
var parsDot = vis.network.convertDot(dotStr);
var data = {
nodes: parsDot.nodes,
edges: parsDot.edges
}
var options = {
layout: {
hierarchical: {
levelSeparation: 100,
nodeSpacing: 100,
parentCentralization: true,
direction: 'UD', // UD, DU, LR, RL
sortMethod: 'directed', // hubsize, directed
//shakeTowards: 'roots' // roots, leaves
},
},
};
let chart = document.getElementById('tree');
var network = new vis.Network(chart, data, options);
let div = document.getElementById("training-charts");
div.style.display = "none";
div = document.getElementById("prediction-charts");
div.style.display = "none";
div = document.getElementById("tree-charts");
div.style.display = "block";
}
break;
case "bayes":
{
const prediction = naiveBayesModel.predictedResult[0];
const probability = Number(naiveBayesModel.predictedResult[1].split('%')[0]);
configureBarChart('predicted-chart', 'Prediccion', [prediction, 'Otros'], 'Probabilidad', [probability, 100 - probability]);
}
break;
case "neural":
{
const elementA = neuralNetworkModel.predictedResult[0];
const elementB = neuralNetworkModel.predictedResult[1];
configureBarChart('predicted-chart', 'Prediccion', ['Elemento A', 'Elemento B'], 'Probabilidad', [elementA, elementB]);
}
break;
case "kmeans":
break;
case "knearest":
break;
}
}
//----------------------------------------------
class CsvController {
constructor(csvContent) {
this.csvContent = csvContent
}
getHeaders() {
return this.csvContent.split('\n')[0].trim().split(';');
}
getNumberDataFromColumn(columnName) {
const headers = this.getHeaders();
let index = 0;
for (index = 0; index < headers.length; index++) {
if (headers[index] === columnName) {
break;
}
}
if (index >= headers.length) {
return null;
}
const rows = this.csvContent.split('\n');
let tempArray = [];
let firstRow = true;
rows.forEach((row) => {
if (firstRow) {
firstRow = false;
return;
}
const element = row.trim().split(';')[index];
element ? tempArray.push(Number(element)) : null;
})
return tempArray;
}
getStringDataFromColumn(columnName) {
const headers = this.getHeaders();
let index = 0;
for (index = 0; index < headers.length; index++) {
if (headers[index] === columnName) {
break;
}
}
if (index >= headers.length) {
return null;
}
const rows = this.csvContent.split('\n');
let tempArray = [];
let firstRow = true;
rows.forEach((row) => {
if (firstRow) {
firstRow = false;
return;
}
const element = row.trim().split(';')[index];
element ? tempArray.push(element) : null;
})
return tempArray;
}
}
//----------------------------------------------
class LinearRegressionAdapter {
constructor() {
this.linearRegression = new LinearRegression();
this.predictXData = null;
this.predictedYData = null;
}
train(trainingXData, trainingYData) {
console.log("trainingXData: ");
console.log(trainingXData);
console.log("trainingYData: ");
console.log(trainingYData);
this.linearRegression.fit(trainingXData, trainingYData);
}
predict(predictXData) {
console.log("predictXData: ");
console.log(predictXData);
this.predictXData = predictXData;
this.predictedYData = this.linearRegression.predict(predictXData);
return this.predictedYData;
}
}
//----------------------------------------------
class PolynomialRegressionAdapter {
constructor() {
this.linearRegression = new PolynomialRegression();
this.predictXData = null;
this.predictedYData = null;
}
trainTwoGradeRegression(trainingXData, trainingYData) {
console.log("trainingXData: ");
console.log(trainingXData);
console.log("trainingYData: ");
console.log(trainingYData);
this.linearRegression.fit(trainingXData, trainingYData, 2);
}
trainThreeGradeRegression(trainingXData, trainingYData) {
console.log("trainingXData: ");
console.log(trainingXData);
console.log("trainingYData: ");
console.log(trainingYData);
this.linearRegression.fit(trainingXData, trainingYData, 3);
}
trainFourGradeRegression(trainingXData, trainingYData) {
console.log("trainingXData: ");
console.log(trainingXData);
console.log("trainingYData: ");
console.log(trainingYData);
this.linearRegression.fit(trainingXData, trainingYData, 4);
}
predict(predictXData) {
console.log("predictXData: ");
console.log(predictXData);
this.predictXData = predictXData;
this.predictedYData = this.linearRegression.predict(predictXData);
return this.predictedYData;
}
}
//----------------------------------------------
class DecisionTreeID3Adapter {
constructor(dataSet) {
this.decisionTree = new DecisionTreeID3(dataSet);
this.predictDataset = null;
this.predictedResult = null;
this.rootTree = null;
}
train() {
console.log("Decision-Tree TrainingDataset:");
console.log(this.decisionTree.dataset);
this.rootTree = this.decisionTree.train(this.decisionTree.dataset);
}
predict(dataSet) {
console.log("Decision-Tree PredictingDataset:");
console.log(dataSet);
this.predictDataset = dataSet;
this.predictedResult = this.decisionTree.predict(dataSet, this.rootTree);
return this.predictedResult;
}
generateDotString() {
return this.decisionTree.generateDotString(this.rootTree);
}
}
//----------------------------------------------
class NaiveBayesAdapter {
constructor() {
this.naiveBayes = new NaiveBayes();
this.variable = null;
this.causes = null;
this.predictedResult = null;
}
insertCause(atribute, values) {
this.naiveBayes.insertCause(atribute, values);
}
predict(variable, causes) {
console.log("Predict effect on '" + variable + "'' with the causes:")
console.log(causes);
this.variable = variable;
this.causes = causes;
this.predictedResult = this.naiveBayes.predict(variable, causes);
return this.predictedResult;
}
}
//----------------------------------------------
class NeuralNetworkAdapter {
constructor() {
this.neuralNetwork = new NeuralNetwork([2, 4, 3, 2]);
this.elementsCompared = null;
this.predictedResult = null;
}
trainHigherElementsCase() {
console.log('Training higuer element case')
for (let i = 0; i < 10000; i++) {
let numero1 = Math.random();
let numero2 = Math.random();
this.neuralNetwork.Entrenar([numero1, numero2], (numero1 > numero2 ? [1, 0] : [0, 1]));
}
}
trainLowerElementsCase() {
console.log('Training lower element case')
for (let i = 0; i < 10000; i++) {
let numero1 = Math.random();
let numero2 = Math.random();
this.neuralNetwork.Entrenar([numero1, numero2], (numero1 < numero2 ? [1, 0] : [0, 1]));
}
}
predict(elementA, elementB) {
console.log("Decision-Tree PredictingDataset:");
console.log([elementA, elementB]);
this.elementsCompared = [elementA, elementB];
this.predictedResult = this.neuralNetwork.Predecir([elementA, elementB]);
return this.predictedResult;
}
}
//----------------------------------------------