Repository navigation
Expand file tree
/
Copy pathSVM.html
More file actions
760 lines (644 loc) · 31.8 KB
/
Copy pathSVM.html
File metadata and controls
760 lines (644 loc) · 31.8 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Support Vector Machine (SVM) Sandbox</title>
<style>
:root {
--primary: #2563eb;
--class-a: #dc2626; /* Pure Red */
--class-b: #2563eb; /* Pure Blue */
/* Light matching variations for Confusion Matrix cells */
--cm-red-correct: #fee2e2; /* Soft red background for TP (Actual Red / Pred Red) */
--cm-red-text: #991b1b;
--cm-blue-correct: #dbeafe; /* Soft blue background for TN (Actual Blue / Pred Blue) */
--cm-blue-text: #1e40af;
--cm-error: #f1f5f9; /* Neutral light gray for misclassifications */
--cm-error-text: #475569;
--background: #f8fafc;
--card: #ffffff;
--text: #1e293b;
--border: #e2e8f0;
}
body {
font-family: system-ui, -apple-system, sans-serif;
background-color: var(--background);
color: var(--text);
margin: 0;
padding: 20px;
}
.container {
max-width: 1300px;
margin: 0 auto;
}
header {
text-align: center;
margin-bottom: 25px;
}
h1 { margin-bottom: 5px; color: #0f172a; }
p { color: #64748b; margin-top: 0; }
.layout {
display: grid;
grid-template-columns: 1fr 420px;
gap: 20px;
}
@media (max-width: 1150px) {
.layout { grid-template-columns: 1fr; }
}
.card {
background: var(--card);
border-radius: 12px;
padding: 20px;
box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05);
border: 1px solid var(--border);
}
.canvas-container {
position: relative;
width: 100%;
background: #ffffff;
border: 1px solid #cbd5e1;
border-radius: 8px;
overflow: hidden;
cursor: crosshair;
}
canvas {
display: block;
width: 100%;
height: 480px;
}
/* Confusion Matrix Grid layout */
.matrix-container {
display: grid;
grid-template-columns: 100px 1fr 1fr 80px;
grid-template-rows: 40px 1fr 1fr 60px;
gap: 8px;
margin: 15px 0;
text-align: center;
align-items: stretch;
}
.matrix-label {
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
font-size: 0.85rem;
color: #475569;
}
.matrix-box {
padding: 12px 5px;
border-radius: 8px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
box-shadow: inset 0 0 4px rgba(0,0,0,0.05);
transition: all 0.2s;
}
.box-tp { background-color: var(--cm-red-correct); color: var(--cm-red-text); }
.box-tn { background-color: var(--cm-blue-correct); color: var(--cm-blue-text); }
.box-fp { background-color: var(--cm-error); color: var(--cm-error-text); }
.box-fn { background-color: var(--cm-error); color: var(--cm-error-text); }
.matrix-count { font-size: 1.5rem; font-weight: 800; }
.matrix-pct { font-size: 0.85rem; font-weight: 600; opacity: 0.9; margin-top: 2px; }
.matrix-title { font-size: 0.7rem; font-weight: 600; opacity: 0.85; text-transform: uppercase; letter-spacing: 0.05em; margin-top: 4px; }
.matrix-total-cell {
display: flex;
justify-content: center;
align-items: center;
background: #e2e8f0;
border-radius: 8px;
font-weight: bold;
color: #334155;
font-size: 1.1rem;
}
.controls {
display: flex;
flex-direction: column;
gap: 15px;
}
.control-group {
display: flex;
flex-direction: column;
gap: 6px;
}
label {
font-weight: 700;
font-size: 0.9rem;
}
.radio-group {
display: flex;
gap: 10px;
margin-bottom: 5px;
}
.radio-label {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 10px;
border-radius: 6px;
border: 2px solid #cbd5e1;
cursor: pointer;
font-weight: 600;
font-size: 0.85rem;
transition: all 0.2s;
}
.toggle-group-wrap {
display: flex;
background: #e2e8f0;
padding: 4px;
border-radius: 8px;
margin-bottom: 5px;
}
.toggle-label {
flex: 1;
text-align: center;
padding: 8px;
font-size: 0.85rem;
font-weight: 700;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
color: #475569;
}
input[type="radio"] { display: none; }
#classA-label { color: var(--class-a); }
#classA-radio:checked + #classA-label { border-color: var(--class-a); background: #fef2f2; }
#classB-label { color: var(--class-b); }
#classB-radio:checked + #classB-label { border-color: var(--class-b); background: #eff6ff; }
#toleranceHard:checked ~ .toggle-group-wrap label[for="toleranceHard"],
#toleranceSoft:checked ~ .toggle-group-wrap label[for="toleranceSoft"],
#metricTargetA:checked ~ .metric-toggle-group label[for="metricTargetA"],
#metricTargetB:checked ~ .metric-toggle-group label[for="metricTargetB"] {
background: #ffffff;
color: #0f172a;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
button {
padding: 10px 14px;
border: none;
border-radius: 6px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
font-size: 0.85rem;
}
.btn-secondary { background: #f1f5f9; color: #334155; border: 1px solid #cbd5e1; }
.btn-secondary:hover { background: #e2e8f0; }
.btn-danger { background: #ef4444; color: white; }
.btn-danger:hover { background: #dc2626; }
.status-box {
background: #f8fafc;
border-left: 4px solid var(--primary);
padding: 12px;
border-radius: 4px;
font-size: 0.85rem;
line-height: 1.4;
border-top: 1px solid var(--border);
border-right: 1px solid var(--border);
border-bottom: 1px solid var(--border);
}
.legend {
display: flex;
gap: 15px;
font-size: 0.8rem;
font-weight: bold;
justify-content: center;
margin-top: 5px;
}
.legend-item { display: flex; align-items: center; gap: 5px; }
.color-line { width: 20px; height: 3px; display: inline-block; }
.color-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; }
/* Metrics grid layout */
.metrics-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-top: 5px;
}
.metric-card {
background: #f8fafc;
border: 1px solid #e2e8f0;
padding: 12px;
border-radius: 8px;
text-align: center;
}
.metric-value { font-size: 1.4rem; font-weight: bold; color: var(--primary); margin-top: 2px;}
.metric-name { font-size: 0.75rem; font-weight: bold; color: #64748b; text-transform: uppercase;}
</style>
</head>
<body>
<div class="container">
<header>
<h1>Linear Support Vector Machine (SVM) Sandbox</h1>
<p>Explore maximum-margin classification, hyperplanes, margins, and support vectors interactively.</p>
</header>
<div class="layout">
<div class="card" style="display: flex; flex-direction: column; gap: 10px;">
<div class="canvas-container" id="canvasWrapper">
<canvas id="svmCanvas"></canvas>
</div>
<div class="legend">
<div class="legend-item"><span class="color-line" style="background:#0f172a"></span> Hyperplane (Decision Boundary)</div>
<div class="legend-item"><span class="color-line" style="background:#94a3b8; border-top: 2px dashed #94a3b8; height:0;"></span> Margins (Gutters)</div>
<div class="legend-item"><span class="color-dot" style="border: 2px solid #0f172a; background:#fff; width:8px; height:8px;"></span> Support Vectors</div>
</div>
<hr style="width:100%; border:0; border-top:1px solid var(--border); margin:5px 0;">
<div style="text-align: center; font-weight: bold; font-size: 0.9rem; color: #475569;">Confusion Matrix (Training Set Evaluation)</div>
<div class="matrix-container">
<div class="matrix-label"></div>
<div class="matrix-label" style="color: var(--class-a);">Predicted Red (+)</div>
<div class="matrix-label" style="color: var(--class-b);">Predicted Blue (-)</div>
<div class="matrix-label" style="color: #475569;">Total</div>
<div class="matrix-label" style="text-align: right; padding-right:10px; justify-content: flex-end; color: var(--class-a);">Actual Red</div>
<div class="matrix-box box-tp" id="m-tp">
<span class="matrix-count" id="count-tp">0</span>
<span class="matrix-pct" id="pct-tp">0.0%</span>
<span class="matrix-title">True Red (TP)</span>
</div>
<div class="matrix-box box-fn" id="m-fn">
<span class="matrix-count" id="count-fn">0</span>
<span class="matrix-pct" id="pct-fn">0.0%</span>
<span class="matrix-title">False Blue (FN)</span>
</div>
<div class="matrix-total-cell" id="total-row-pos">0</div>
<div class="matrix-label" style="text-align: right; padding-right:10px; justify-content: flex-end; color: var(--class-b);">Actual Blue</div>
<div class="matrix-box box-fp" id="m-fp">
<span class="matrix-count" id="count-fp">0</span>
<span class="matrix-pct" id="pct-fp">0.0%</span>
<span class="matrix-title">False Red (FP)</span>
</div>
<div class="matrix-box box-tn" id="m-tn">
<span class="matrix-count" id="count-tn">0</span>
<span class="matrix-pct" id="pct-tn">0.0%</span>
<span class="matrix-title">True Blue (TN)</span>
</div>
<div class="matrix-total-cell" id="total-row-neg">0</div>
<div class="matrix-label" style="color: #475569;">Total</div>
<div class="matrix-total-cell" id="total-col-pos">0</div>
<div class="matrix-total-cell" id="total-col-neg">0</div>
<div class="matrix-total-cell" id="total-grand" style="background-color: #cbd5e1; color: #0f172a;">0</div>
</div>
</div>
<div class="card controls">
<div class="control-group">
<label>1. Select Class to Plot</label>
<div class="radio-group">
<input type="radio" id="classA-radio" name="classSelect" value="1" checked>
<label for="classA-radio" id="classA-label" class="radio-label">
<span class="color-dot" style="background:var(--class-a)"></span> Class +1 (Red)
</label>
<input type="radio" id="classB-radio" name="classSelect" value="-1">
<label for="classB-radio" id="classB-label" class="radio-label">
<span class="color-dot" style="background:var(--class-b)"></span> Class -1 (Blue)
</label>
</div>
</div>
<div class="control-group">
<label>2. Classification Error Tolerance Mode</label>
<input type="radio" id="toleranceHard" name="toleranceSelect" value="hard" checked>
<input type="radio" id="toleranceSoft" name="toleranceSelect" value="soft">
<div class="toggle-group-wrap">
<label for="toleranceHard" class="toggle-label">Hard Margin (No Errors)</label>
<label for="toleranceSoft" class="toggle-label">Soft Margin (Allow Slack)</label>
</div>
<span style="font-size:0.7rem; color:#64748b;">Hard margin forces absolute separation (will report non-separable on overlapping points). Soft margin uses relaxation slack to find a boundary amidst noise.</span>
</div>
<button id="btnSample" class="btn-secondary">Load Linearly Separable Sample</button>
<button id="btnClear" class="btn-danger">Clear Graph Canvas</button>
<hr style="width:100%; border:0; border-top:1px solid var(--border); margin:5px 0;">
<div class="control-group">
<label>3. Select Target Focus Class for Metrics Calculations</label>
<input type="radio" id="metricTargetA" name="metricClassTarget" value="1" checked>
<input type="radio" id="metricClassTarget" id="metricTargetB" name="metricClassTarget" value="-1">
<div class="metric-toggle-group toggle-group-wrap">
<label for="metricTargetA" class="toggle-label">Red Class (+)</label>
<label for="metricTargetB" class="toggle-label">Blue Class (-)</label>
</div>
</div>
<div class="control-group">
<label>Derived Evaluation Metrics Calculations</label>
<div class="metrics-grid">
<div class="metric-card" title="Accuracy = (TP + TN) / Total">
<div class="metric-name">Accuracy</div>
<div class="metric-value" id="mVal-accuracy">0.0%</div>
</div>
<div class="metric-card" id="precision-card-desc" title="Precision = TP / (TP + FP)">
<div class="metric-name" id="precision-label-text">Precision</div>
<div class="metric-value" id="mVal-precision">0.0%</div>
</div>
<div class="metric-card" id="recall-card-desc" title="Recall (Sensitivity) = TP / (TP + FN)">
<div class="metric-name" id="recall-label-text">Sensitivity (Recall)</div>
<div class="metric-value" id="mVal-recall">0.0%</div>
</div>
<div class="metric-card" id="specificity-card-desc" title="Specificity = TN / (TN + FP)">
<div class="metric-name" id="specificity-label-text">Specificity</div>
<div class="metric-value" id="mVal-specificity">0.0%</div>
</div>
</div>
</div>
<hr style="width:100%; border:0; border-top:1px solid var(--border); margin:5px 0;">
<div class="status-box" id="hudStatus">
<strong>Model Status: Ready</strong><br>
Click inside the data plane grid to manually plot coordinates. Try making two separate clusters to generate an optimal boundary corridor!
</div>
<div class="card" style="background:#f8fafc; padding:12px; font-size:0.8rem; box-shadow:none; line-height:1.4;">
<strong>💡 Classroom Experiment:</strong> Toggle over to **Soft Margin** when working with messy or non-separable datasets. Notice how the model avoids crashing and instead constructs a stable decision corridor, minimizing error using an automated subgradient optimization routine!
</div>
</div>
</div>
</div>
<script>
const canvas = document.getElementById('svmCanvas');
const ctx = canvas.getContext('2d');
const btnSample = document.getElementById('btnSample');
const btnClear = document.getElementById('btnClear');
const hudStatus = document.getElementById('hudStatus');
const toleranceHard = document.getElementById('toleranceHard');
const toleranceSoft = document.getElementById('toleranceSoft');
const metricTargetA = document.getElementById('metricTargetA');
const metricTargetB = document.getElementById('metricTargetB');
// Confusion Matrix anchors
const countTp = document.getElementById('count-tp');
const countTn = document.getElementById('count-tn');
const countFp = document.getElementById('count-fp');
const countFn = document.getElementById('count-fn');
const pctTp = document.getElementById('pct-tp');
const pctTn = document.getElementById('pct-tn');
const pctFp = document.getElementById('pct-fp');
const pctFn = document.getElementById('pct-fn');
const totalRowPos = document.getElementById('total-row-pos');
const totalRowNeg = document.getElementById('total-row-neg');
const totalColPos = document.getElementById('total-col-pos');
const totalColNeg = document.getElementById('total-col-neg');
const totalGrand = document.getElementById('total-grand');
// Metrics anchors
const mValAccuracy = document.getElementById('mVal-accuracy');
const mValPrecision = document.getElementById('mVal-precision');
const mValRecall = document.getElementById('mVal-recall');
const mValSpecificity = document.getElementById('mVal-specificity');
const precisionLabelText = document.getElementById('precision-label-text');
const recallLabelText = document.getElementById('recall-label-text');
const specificityLabelText = document.getElementById('specificity-label-text');
const precisionCardDesc = document.getElementById('precision-card-desc');
const recallCardDesc = document.getElementById('recall-card-desc');
const specificityCardDesc = document.getElementById('specificity-card-desc');
let points = [];
let w = [0, 0];
let b = 0;
let supportVectors = [];
let isSeparable = false;
const HEX_RED = '#dc2626';
const HEX_BLUE = '#2563eb';
function resizeCanvas() {
canvas.width = canvas.offsetWidth;
canvas.height = 480;
if(points.length === 0) loadSampleDataset();
else {
trainLinearSVM();
render();
}
}
window.addEventListener('resize', resizeCanvas);
canvas.addEventListener('click', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const label = document.querySelector('input[name="classSelect"]:checked').value === "1" ? 1 : -1;
points.push({ x, y, label });
trainLinearSVM();
render();
});
function loadSampleDataset() {
points = [];
const w_c = canvas.width;
const h_c = canvas.height;
// Class +1 (Red, top left quadrant region)
points.push({ x: w_c * 0.25, y: h_c * 0.25, label: 1 });
points.push({ x: w_c * 0.35, y: h_c * 0.15, label: 1 });
points.push({ x: w_c * 0.20, y: h_c * 0.40, label: 1 });
points.push({ x: w_c * 0.40, y: h_c * 0.35, label: 1 });
// Class -1 (Blue, bottom right quadrant region)
points.push({ x: w_c * 0.65, y: h_c * 0.75, label: -1 });
points.push({ x: w_c * 0.75, y: h_c * 0.65, label: -1 });
points.push({ x: w_c * 0.60, y: h_c * 0.60, label: -1 });
points.push({ x: w_c * 0.80, y: h_c * 0.85, label: -1 });
trainLinearSVM();
render();
}
function trainLinearSVM() {
if (points.length < 2) {
isSeparable = false;
evaluateConfusionMatrixAndMetrics(0, 0, 0, 0);
return;
}
w = [0, 0];
b = 0;
let lr = 0.1;
const epochs = 15000;
// C constant controls error regulation weight in Soft margin constraints model mapping rules
const isSoftMargin = document.querySelector('input[name="toleranceSelect"]:checked').value === "soft";
const lambda = isSoftMargin ? 0.01 : 0.0001;
for (let epoch = 1; epoch <= epochs; epoch++) {
let currentLr = lr / (1 + epoch * 0.0001);
let p = points[Math.floor(Math.random() * points.length)];
let nx = p.x / canvas.width;
let ny = p.y / canvas.height;
let classificationDecision = p.label * ((w[0] * nx + w[1] * ny) + b);
if (classificationDecision < 1) {
w[0] = (1 - currentLr * lambda) * w[0] + currentLr * p.label * nx;
w[1] = (1 - currentLr * lambda) * w[1] + currentLr * p.label * ny;
b = b + currentLr * p.label;
} else {
w[0] = (1 - currentLr * lambda) * w[0];
w[1] = (1 - currentLr * lambda) * w[1];
}
}
let cleanSeparation = true;
supportVectors = [];
const thresholdMarginError = 1.05;
points.forEach(p => {
let nx = p.x / canvas.width;
let ny = p.y / canvas.height;
let score = p.label * ((w[0] * nx + w[1] * ny) + b);
if (score < 0.0) cleanSeparation = false;
if (score <= thresholdMarginError) {
supportVectors.push(p);
}
});
// Hard margin forces absolute linear partition conditions constraint bounds validation checking
if (!isSoftMargin && !cleanSeparation) {
isSeparable = false;
} else {
isSeparable = true;
}
updateHUDStatus();
calculateGlobalConfusionMatrix();
}
function updateHUDStatus() {
const isSoftMargin = document.querySelector('input[name="toleranceSelect"]:checked').value === "soft";
if (points.length < 2) {
hudStatus.style.borderColor = "#cbd5e1"; hudStatus.style.background = "#f1f5f9";
hudStatus.innerHTML = `<strong>Model Status: Awaiting Data</strong><br>Plot at least one point for both classes to project hyperplanes.`;
} else if (!isSeparable && !isSoftMargin) {
hudStatus.style.borderColor = "#dc2626"; hudStatus.style.background = "#fef2f2";
hudStatus.innerHTML = `<strong>⚠️ Data is Linearly Non-Separable!</strong><br>The points overlap so a clean straight line cannot perfectly divide them under Hard Margin constraints. Enable <b>Soft Margin mode</b> above to calculate an optimal relaxed corridor!`;
} else if (isSoftMargin) {
hudStatus.style.borderColor = "#2563eb"; hudStatus.style.background = "#eff6ff";
hudStatus.innerHTML = `<strong>🎯 Soft Margin Convergence Active</strong><br>Decision boundary balanced successfully by minimizing slack margin violations via subgradients. Boundary uses <b>${supportVectors.length} boundary support samples</b>.`;
} else {
hudStatus.style.borderColor = "#16a34a"; hudStatus.style.background = "#f0fdf4";
hudStatus.innerHTML = `<strong>🎯 Convex Optimization Converged!</strong><br>
Hyperplane locked successfully. Maximum margin width established using <b>${supportVectors.length} support vectors</b>.`;
}
}
// --- EVALUATION CONFUSION MATRIX MECHANICS ENGINE ---
function calculateGlobalConfusionMatrix() {
let tp = 0, tn = 0, fp = 0, fn = 0;
points.forEach(p => {
let nx = p.x / canvas.width;
let ny = p.y / canvas.height;
let score = (w[0] * nx + w[1] * ny) + b;
let predLabel = score >= 0 ? 1 : -1;
if (p.label === 1 && predLabel === 1) tp++;
else if (p.label === -1 && predLabel === -1) tn++;
else if (p.label === -1 && predLabel === 1) fp++;
else if (p.label === 1 && predLabel === -1) fn++;
});
evaluateConfusionMatrixAndMetrics(tp, tn, fp, fn);
}
function evaluateConfusionMatrixAndMetrics(tp, tn, fp, fn) {
countTp.innerText = tp;
countTn.innerText = tn;
countFp.innerText = fp;
countFn.innerText = fn;
let rowPosTotal = tp + fn;
let rowNegTotal = fp + tn;
let colPosTotal = tp + fp;
let colNegTotal = fn + tn;
let grandTotal = tp + tn + fp + fn;
totalRowPos.innerText = rowPosTotal;
totalRowNeg.innerText = rowNegTotal;
totalColPos.innerText = colPosTotal;
totalColNeg.innerText = colNegTotal;
totalGrand.innerText = grandTotal;
let tpPct = rowPosTotal > 0 ? (tp / rowPosTotal * 100).toFixed(1) : '0.0';
let fnPct = rowPosTotal > 0 ? (fn / rowPosTotal * 100).toFixed(1) : '0.0';
let fpPct = rowNegTotal > 0 ? (fp / rowNegTotal * 100).toFixed(1) : '0.0';
let tnPct = rowNegTotal > 0 ? (tn / rowNegTotal * 100).toFixed(1) : '0.0';
pctTp.innerText = `${tpPct}%`;
pctFn.innerText = `${fnPct}%`;
pctFp.innerText = `${fpPct}%`;
pctTn.innerText = `${tnPct}%`;
// Calculate global summary rates metrics calculations
let accuracy = grandTotal > 0 ? (tp + tn) / grandTotal : 0;
mValAccuracy.innerText = `${(accuracy * 100).toFixed(1)}%`;
const targetClassIsPositive = document.querySelector('input[name="metricClassTarget"]:checked').value === "1";
if (targetClassIsPositive) {
precisionLabelText.innerText = "Precision";
recallLabelText.innerText = "Sensitivity (Recall)";
specificityLabelText.innerText = "Specificity";
precisionCardDesc.title = "Precision = TP / (TP + FP)";
recallCardDesc.title = "Sensitivity = TP / (TP + FN)";
specificityCardDesc.title = "Specificity = TN / (TN + FP)";
let precision = (tp + fp) > 0 ? tp / (tp + fp) : 0;
let recall = (tp + fn) > 0 ? tp / (tp + fn) : 0;
let specificity = (tn + fp) > 0 ? tn / (tn + fp) : 0;
mValPrecision.innerText = (tp + fp) > 0 ? `${(precision * 100).toFixed(1)}%` : "0.0%";
mValRecall.innerText = (tp + fn) > 0 ? `${(recall * 100).toFixed(1)}%` : "0.0%";
mValSpecificity.innerText = (tn + fp) > 0 ? `${(specificity * 100).toFixed(1)}%` : "0.0%";
} else {
precisionLabelText.innerText = "Precision (-)";
recallLabelText.innerText = "Specificity (Recall -)";
specificityLabelText.innerText = "Sensitivity (-)";
precisionCardDesc.title = "Precision (-) = TN / (TN + FN)";
recallCardDesc.title = "Specificity (Recall -) = TN / (TN + FP)";
specificityCardDesc.title = "Sensitivity (-) = TP / (TP + FN)";
let precisionNeg = (tn + fn) > 0 ? tn / (tn + fn) : 0;
let recallNeg = (tn + fp) > 0 ? tn / (tn + fp) : 0;
let specificityNeg = (tp + fn) > 0 ? tp / (tp + fn) : 0;
mValPrecision.innerText = (tn + fn) > 0 ? `${(precisionNeg * 100).toFixed(1)}%` : "0.0%";
mValRecall.innerText = (tn + fp) > 0 ? `${(recallNeg * 100).toFixed(1)}%` : "0.0%";
mValSpecificity.innerText = (tp + fn) > 0 ? `${(specificityNeg * 100).toFixed(1)}%` : "0.0%";
}
}
// --- GRAPHICAL CANVAS PLOTTER ---
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Grid lines backdrop mesh
ctx.strokeStyle = '#f1f5f9'; ctx.lineWidth = 1;
for (let i = 40; i < canvas.width; i += 40) { ctx.beginPath(); ctx.moveTo(i, 0); ctx.lineTo(i, canvas.height); ctx.stroke(); }
for (let i = 40; i < canvas.height; i += 40) { ctx.beginPath(); ctx.moveTo(0, i); ctx.lineTo(canvas.width, i); ctx.stroke(); }
// Draw boundaries contours layers planes
if (isSeparable && (w[0] !== 0 || w[1] !== 0)) {
drawLinearContour(0, '#0f172a', 3, false);
drawLinearContour(1, '#94a3b8', 1.5, true);
drawLinearContour(-1, '#94a3b8', 1.5, true);
}
// Draw Data Points
points.forEach(p => {
ctx.beginPath();
ctx.arc(p.x, p.y, 8, 0, Math.PI * 2);
ctx.fillStyle = p.label === 1 ? HEX_RED : HEX_BLUE;
ctx.fill();
ctx.strokeStyle = '#ffffff'; ctx.lineWidth = 1.5; ctx.stroke();
// Highlight support vectors nodes rings
if (isSeparable && supportVectors.includes(p)) {
ctx.beginPath();
ctx.arc(p.x, p.y, 14, 0, Math.PI * 2);
ctx.strokeStyle = '#0f172a';
ctx.lineWidth = 2;
ctx.stroke();
}
});
}
function drawLinearContour(marginOffsetTarget, color, thickness, isDashed) {
ctx.strokeStyle = color;
ctx.lineWidth = thickness;
if(isDashed) ctx.setLineDash([6, 6]);
else ctx.setLineDash([]);
ctx.beginPath();
let pointFoundCount = 0;
let xLeft = 0;
let yLeft = canvas.height * (-b + marginOffsetTarget) / w[1];
if (yLeft >= 0 && yLeft <= canvas.height) {
ctx.moveTo(xLeft, yLeft); pointFoundCount++;
}
let xRight = canvas.width;
let yRight = canvas.height * (-w[0] * 1.0 - b + marginOffsetTarget) / w[1];
if (yRight >= 0 && yRight <= canvas.height) {
if(pointFoundCount === 0) ctx.moveTo(xRight, yRight);
else ctx.lineTo(xRight, yRight);
pointFoundCount++;
}
let yTop = 0;
let xTop = canvas.width * (-b + marginOffsetTarget) / w[0];
if (xTop >= 0 && xTop <= canvas.width && pointFoundCount < 2) {
if(pointFoundCount === 0) ctx.moveTo(xTop, yTop);
else ctx.lineTo(xTop, yTop);
pointFoundCount++;
}
let yBottom = canvas.height;
let xBottom = canvas.width * (-w[1] * 1.0 - b + marginOffsetTarget) / w[0];
if (xBottom >= 0 && xBottom <= canvas.width && pointFoundCount < 2) {
if(pointFoundCount === 0) ctx.moveTo(xBottom, yBottom);
else ctx.lineTo(xBottom, yBottom);
}
ctx.stroke();
ctx.setLineDash([]);
}
// Connect control bindings loops
document.querySelectorAll('input[name="toleranceSelect"]').forEach(radio => {
radio.addEventListener('change', () => { trainLinearSVM(); render(); });
});
document.querySelectorAll('input[name="metricClassTarget"]').forEach(radio => {
radio.addEventListener('change', calculateGlobalConfusionMatrix);
});
btnSample.addEventListener('click', loadSampleDataset);
btnClear.addEventListener('click', () => { points = []; w = [0,0]; b = 0; isSeparable = false; updateHUDStatus(); evaluateConfusionMatrixAndMetrics(0,0,0,0); render(); });
setTimeout(() => { resizeCanvas(); }, 100);
</script>
</body>
</html>