-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmath_visual_lab.html
More file actions
2097 lines (1887 loc) · 99.1 KB
/
Copy pathmath_visual_lab.html
File metadata and controls
2097 lines (1887 loc) · 99.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Math & Stats Visual Lab</title>
<!-- Shared component styles (additive; page-local <style> below still wins for parity) -->
<link rel="stylesheet" href="lesson-components.css">
<style>
:root {
--bg: #0f1117; --panel: #1a1d27; --border: #2a2d3a;
--accent: #6c63ff; --accent2: #00d4aa; --text: #e8eaf0; --muted: #8890a4;
--red: #ff4d6d; --yellow: #ffd166; --green: #06d6a0;
--orange: #ff9f43; --blue: #4fc3f7; --purple: #c084fc;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body { background: var(--bg); color: var(--text); font-family: 'Segoe UI', system-ui, sans-serif; font-size: 13px; min-height: 100vh; display: flex; flex-direction: column; }
#header { background: var(--panel); border-bottom: 1px solid var(--border); padding: 10px 20px; display: flex; align-items: center; gap: 16px; flex-shrink: 0; }
#header h1 { font-size: 16px; font-weight: 700; color: var(--accent); letter-spacing: 0.5px; }
#header .sub { color: var(--muted); font-size: 11px; }
#header a { color: var(--accent2); font-size: 11px; text-decoration: none; margin-left: auto; }
#layout { display: flex; flex: 1; overflow: hidden; }
#sidebar { width: 220px; flex-shrink: 0; background: var(--panel); border-right: 1px solid var(--border); overflow-y: auto; padding: 12px 10px; }
.nav-label { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 1px; color: var(--muted); margin: 14px 0 6px 4px; }
.nav-btn { display: block; width: 100%; text-align: left; padding: 8px 10px; border-radius: 5px; border: none; background: transparent; color: var(--muted); font-size: 12px; cursor: pointer; margin-bottom: 3px; transition: all 0.15s; }
.nav-btn:hover { background: rgba(255,255,255,0.05); color: var(--text); }
.nav-btn.active { background: rgba(108,99,255,0.18); color: var(--accent); font-weight: 700; }
.nav-num { display: inline-block; width: 20px; height: 20px; border-radius: 50%; background: var(--border); text-align: center; line-height: 20px; font-size: 10px; margin-right: 6px; }
.nav-btn.active .nav-num { background: var(--accent); color: white; }
#content { flex: 1; overflow-y: auto; padding: 20px; }
.section { display: none; }
.section.active { display: block; }
.sec-header { margin-bottom: 18px; }
.sec-title { font-size: 20px; font-weight: 700; color: var(--accent); margin-bottom: 6px; }
.sec-sub { color: var(--muted); font-size: 13px; line-height: 1.6; }
.explain-box { background: rgba(108,99,255,0.07); border: 1px solid rgba(108,99,255,0.25); border-radius: 8px; padding: 14px 16px; font-size: 12px; color: #b8bbcf; line-height: 1.8; margin-bottom: 14px; }
.explain-box strong { color: var(--accent2); }
.math-box { background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 10px 14px; font-family: monospace; font-size: 13px; color: var(--yellow); margin-bottom: 14px; line-height: 1.8; }
.demo-card { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 16px; margin-bottom: 16px; }
.demo-title { font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.8px; color: var(--muted); margin-bottom: 12px; }
canvas { display: block; background: #0a0c12; border-radius: 6px; cursor: crosshair; max-width: 100%; }
.ctrl-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-top: 10px; }
.ctrl-group { display: flex; align-items: center; gap: 6px; }
.ctrl-group label { font-size: 11px; color: var(--muted); white-space: nowrap; }
.ctrl-group input[type=range] { width: 100px; accent-color: var(--accent); cursor: pointer; }
.val-badge { font-size: 11px; font-family: monospace; color: var(--accent2); background: var(--bg); padding: 2px 7px; border-radius: 3px; border: 1px solid var(--border); min-width: 40px; text-align: center; }
.btn { padding: 5px 12px; border-radius: 4px; border: 1px solid var(--border); cursor: pointer; font-size: 11px; font-weight: 600; background: transparent; color: var(--text); transition: all 0.15s; }
.btn:hover { background: var(--border); }
.btn-primary { background: var(--accent); color: white; border-color: var(--accent); }
.btn-primary:hover { opacity: 0.85; }
.btn-green { background: var(--green); color: #000; border-color: var(--green); }
.info-row { display: flex; gap: 12px; margin-top: 10px; flex-wrap: wrap; }
.info-pill { background: var(--bg); border: 1px solid var(--border); border-radius: 4px; padding: 5px 10px; font-size: 11px; font-family: monospace; }
.info-pill span { color: var(--muted); margin-right: 4px; }
.info-pill strong { color: var(--accent2); }
.two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
@media (max-width: 900px) { .two-col { grid-template-columns: 1fr; } #layout { flex-direction: column; } #sidebar { width: 100%; } }
.tag { display: inline-block; font-size: 10px; padding: 2px 6px; border-radius: 3px; font-weight: 700; margin-left: 4px; }
.tag-ml { background: rgba(0,212,170,0.18); color: var(--accent2); }
.dist-btn { padding: 4px 10px; border-radius: 3px; border: 1px solid var(--border); cursor: pointer; font-size: 11px; background: transparent; color: var(--muted); transition: all 0.12s; margin-right: 4px; }
.dist-btn.active { background: var(--accent2); color: #000; border-color: var(--accent2); font-weight: 700; }
select { background: var(--bg); border: 1px solid var(--border); color: var(--text); padding: 4px 8px; border-radius: 4px; font-size: 11px; cursor: pointer; accent-color: var(--accent); }
.link-badge { display: inline-block; font-size: 10px; padding: 2px 8px; border-radius: 10px; background: rgba(108,99,255,0.2); color: var(--accent); font-weight: 700; margin-top: 8px; }
table.cm { border-collapse: collapse; }
table.cm td, table.cm th { border: 1px solid var(--border); padding: 8px 12px; text-align: center; font-size: 12px; }
table.cm th { background: rgba(108,99,255,0.12); color: var(--accent); font-size: 11px; }
.cm-tp { background: rgba(6,214,160,0.15); color: var(--green); font-weight: 700; }
.cm-fp { background: rgba(255,77,109,0.12); color: var(--red); font-weight: 700; }
.cm-fn { background: rgba(255,159,67,0.12); color: var(--orange); font-weight: 700; }
.cm-tn { background: rgba(79,195,247,0.12); color: var(--blue); font-weight: 700; }
/* ── MOBILE RESPONSIVE (extends the 900px breakpoint) ── */
#mobile-sidebar-toggle { display: none; }
@media (max-width: 768px) {
#mobile-sidebar-toggle {
display: flex; align-items: center; gap: 8px;
padding: 8px 16px; background: var(--panel);
border-bottom: 1px solid var(--border);
font-size: 12px; color: var(--accent2); cursor: pointer;
user-select: none; font-weight: 600;
}
#layout { flex-direction: column; overflow: visible; }
#sidebar {
width: 100%; height: auto; display: none;
overflow-x: auto; white-space: nowrap; padding: 8px;
border-right: none; border-bottom: 1px solid var(--border);
}
#sidebar.mobile-open { display: block; }
#sidebar .nav-btn { display: inline-block; width: auto; white-space: nowrap; margin-right: 4px; }
#content { overflow-y: visible; padding: 12px; }
canvas { max-width: 100%; height: auto !important; }
table.cm { display: block; overflow-x: auto; }
.ctrl-row { flex-wrap: wrap; gap: 8px; }
button, .btn { min-height: 40px; }
#header { padding: 8px 12px; flex-wrap: wrap; }
#header h1 { font-size: 14px; }
}
@media (max-width: 480px) {
#content { padding: 8px; }
.demo-card { padding: 12px; }
canvas { max-width: 100%; }
#header h1 { font-size: 13px; }
}
/* ── NARRATIVE WRAPPER: lesson-tabs strip + prose (additive 2026-06) ── */
/* Live viz host (#layout) + its mobile toggle are hidden unless the Lab tab is
active. JS toggles body.lab-active; default (no class) hides the host so the
prose tabs show first. */
body:not(.lab-active) #layout,
body:not(.lab-active) #mobile-sidebar-toggle { display: none; }
#lesson-tabs-bar {
display: flex; flex-wrap: wrap; gap: 0;
background: var(--panel); border-bottom: 1px solid var(--border);
padding: 0 20px; overflow-x: auto;
}
.nav-tab {
padding: 10px 14px; font-size: 11px; font-weight: 600; color: var(--muted);
cursor: pointer; background: none; border: none; border-bottom: 2px solid transparent;
white-space: nowrap; transition: color 0.15s, border-color 0.15s; min-height: 40px;
}
.nav-tab:hover { color: var(--text); }
.nav-tab.active, .nav-tab[aria-selected="true"] { color: var(--accent); border-bottom-color: var(--accent); }
.nav-tab:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.lesson-narrative { padding: 22px 24px 8px; max-width: 940px; }
.lesson-narrative[hidden] { display: none; }
.nar-h2 { font-size: 20px; font-weight: 700; color: var(--accent); margin-bottom: 6px; }
.nar-intro { color: var(--muted); font-size: 13px; line-height: 1.7; margin-bottom: 18px; }
.nar-card {
background: var(--panel); border: 1px solid var(--border); border-radius: 10px;
padding: 16px 18px; margin-bottom: 16px;
}
.nar-card h3 { font-size: 13px; font-weight: 700; color: var(--accent2); margin-bottom: 8px; }
.nar-card p { color: #c9d1d9; font-size: 13px; line-height: 1.75; margin-bottom: 8px; }
.nar-card p:last-child { margin-bottom: 0; }
.nar-card code { background: var(--bg); color: var(--yellow); padding: 1px 5px; border-radius: 3px; font-size: 12px; }
/* prereq grid (mirrors lesson-components.css .prereq-* hooks, in this page's palette) */
.prereq-row {
display: grid; grid-template-columns: 200px 1fr; gap: 0;
border: 1px solid var(--border); border-radius: 6px; overflow: hidden; margin-bottom: 10px;
}
.prereq-concept {
background: rgba(108,99,255,0.08); padding: 11px 14px; font-weight: 700; font-size: 12px;
color: var(--accent); border-right: 1px solid var(--border); display: flex; align-items: center;
}
.prereq-why { padding: 11px 14px; font-size: 12px; color: var(--text); line-height: 1.6; }
.prereq-why a { color: var(--accent2); text-decoration: none; }
.prereq-why a:hover { text-decoration: underline; }
/* worked-example box: a step-by-step hand computation */
.worked-box {
background: rgba(0,212,170,0.06); border: 1px solid rgba(0,212,170,0.28);
border-left: 3px solid var(--accent2); border-radius: 8px; padding: 14px 16px; margin-bottom: 16px;
}
.worked-box .worked-label {
font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.8px;
color: var(--accent2); margin-bottom: 8px;
}
.worked-box h3 { font-size: 13px; font-weight: 700; color: var(--text); margin-bottom: 8px; }
.worked-step {
font-family: monospace; font-size: 12.5px; color: var(--text); line-height: 2.0;
background: var(--bg); border: 1px solid var(--border); border-radius: 6px;
padding: 10px 14px; margin: 8px 0; overflow-x: auto;
}
.worked-step .res { color: var(--accent2); font-weight: 700; }
.worked-step .cmt { color: var(--muted); }
.worked-box p { color: #c9d1d9; font-size: 12.5px; line-height: 1.7; margin-bottom: 6px; }
.worked-box .try-link {
display: inline-block; margin-top: 6px; font-size: 11px; font-weight: 700;
color: var(--accent); background: rgba(108,99,255,0.14);
border: 1px solid rgba(108,99,255,0.3); border-radius: 6px; padding: 5px 11px; cursor: pointer;
}
.worked-box .try-link:hover { background: rgba(108,99,255,0.24); }
.nar-tip { font-size: 12px; color: var(--muted); line-height: 1.6; }
.nar-tip a { color: var(--accent2); text-decoration: none; }
.nar-tip a:hover { text-decoration: underline; }
@media (max-width: 640px) {
.prereq-row { grid-template-columns: 1fr; }
.prereq-concept { border-right: none; border-bottom: 1px solid var(--border); }
.lesson-narrative { padding: 14px 12px 4px; }
}
</style>
<link rel="stylesheet" href="site-polish.css">
<script src="canvas-hidpi.js"></script>
<script src="catalog.js"></script>
<script src="theme.js" defer></script>
<script src="search.js" defer></script>
<script src="nav.js" defer></script>
<script src="glossary.js" defer></script>
<script src="lesson-tabs.js" defer></script>
</head>
<body>
<div id="header">
<h1>Math & Stats Visual Lab</h1>
<span class="sub">The math behind ML — derivatives, integration, linear algebra, probability, statistics & metrics · plain-English + 12 live demos</span>
<a href="index.html">← Suite Index</a>
</div>
<!-- ══════════════════════════════════════════════════════════════════════
NARRATIVE WRAPPER (additive 2026-06)
Standard data-tab-target/data-tab-panel tabs via lesson-tabs.js.
IMPORTANT: this [data-tabs] root contains ONLY the prose panels +
a small "lab" stub. The live 12-canvas viz host (#layout, with its
OWN selects/sliders/buttons) is kept as a SIBLING below — never a
descendant — so the outer tab controller cannot scan/hijack the
demos' inner controls. A lessontab:change listener toggles #layout
visibility and re-draws the active canvas section when the Lab tab
is revealed. (See the <script> note near the bottom.)
══════════════════════════════════════════════════════════════════════ -->
<div id="narrative-tabs" data-tabs="mathlab" data-tabs-hash data-tab-active-class="active">
<div id="lesson-tabs-bar" role="tablist" aria-label="Lesson sections">
<button class="nav-tab active" data-tab-target="prereq" data-tab-default>1 · Prerequisites</button>
<button class="nav-tab" data-tab-target="intuition">2 · Intuition</button>
<button class="nav-tab" data-tab-target="worked">3 · Worked Examples</button>
<button class="nav-tab" data-tab-target="lab">4 · Interactive Lab</button>
</div>
<!-- ── PANEL 1: PREREQUISITES ── -->
<div id="np-prereq" class="lesson-narrative" data-tab-panel="prereq">
<div class="nar-h2">Prerequisites</div>
<div class="nar-intro">This lab is the math floor everything else in the suite stands on. You do not need a degree — just comfort with a few ideas. If any row below feels shaky, follow its link first, then come back. Everything here is then made concrete by the 12 live demos in the <b>Interactive Lab</b> tab.</div>
<div class="prereq-row">
<div class="prereq-concept">Functions & basic algebra</div>
<div class="prereq-why">A function <code>f(x)</code> takes an input and returns an output (e.g. <code>f(x) = x²</code>). You should be able to plug a number in and read a graph. That is all the algebra the Derivatives, Integration, and Statistics sections assume.</div>
</div>
<div class="prereq-row">
<div class="prereq-concept">What a derivative is</div>
<div class="prereq-why">The <b>derivative</b> <code>f′(x)</code> is the <em>slope</em> of a curve at a point — how fast the output changes as you nudge the input. A <b>gradient</b> is just the derivative generalized to many inputs: a vector of slopes, one per variable. This is the engine of training — every weight update follows the negative gradient. New to it? The intuition is built from scratch in the next tab and in <a href="activation_loss_explorer.html">Activation & Loss Explorer</a> and <a href="optimizer_playground.html">Optimizer Playground</a>.</div>
</div>
<div class="prereq-row">
<div class="prereq-concept">Probability basics</div>
<div class="prereq-why">A probability is a number in <code>[0, 1]</code>; the chances of all outcomes add up to 1. A <b>distribution</b> says how likely each value is. That is enough for the Probability and Statistics sections — the demos show the rest (sampling, the normal curve, the Law of Large Numbers) visually. Softmax, which turns model scores into probabilities, is covered in <a href="activation_loss_explorer.html">Activation & Loss Explorer</a>.</div>
</div>
<div class="prereq-row">
<div class="prereq-concept">Vectors (helpful, not required)</div>
<div class="prereq-why">A <b>vector</b> is just an ordered list of numbers with a direction and length. The Linear Algebra section introduces dot products and matrices visually, so you can pick this up here. For a deeper treatment see <a href="topic_tensors_broadcasting.html">Arrays, Vectors, Tensors & Broadcasting</a>.</div>
</div>
<div class="nar-card" style="border-left:3px solid var(--accent2);">
<h3>Why this lab matters for ML</h3>
<p>Three of these ideas reappear constantly: <b>derivatives/gradients</b> are how a model learns (gradient descent), <b>probability</b> is how a model expresses uncertainty (softmax, sampling, temperature), and <b>statistics</b> is how you understand your data and read training curves. The other two — <b>integration</b> and <b>linear algebra</b> — are the language underneath: every probability is an integral of a density, and every layer, embedding, and attention score is a matrix operation. Get these visual intuitions once and the rest of the suite reads far more easily.</p>
</div>
</div>
<!-- ── PANEL 2: INTUITION (plain-English wrapper around the demos) ── -->
<div id="np-intuition" class="lesson-narrative" data-tab-panel="intuition" hidden>
<div class="nar-h2">Plain-English Intuition</div>
<div class="nar-intro">Each demo in the <b>Interactive Lab</b> tab visualizes one idea. Here is what each one is showing and why it matters for machine learning — read this first, then open the Lab and drag things around to feel it.</div>
<div class="nar-card">
<h3>1 · Derivatives & Gradients <span style="color:var(--muted);font-weight:400;">→ how models learn</span></h3>
<p>The first demo lets you drag a point along a curve and watch the <b>tangent line</b> tilt. The steepness of that line is the derivative — the rate of change. Where the curve is flat, the slope is 0; that is a minimum or maximum. The second demo drops a ball on a 2-D "loss surface": the red arrow is the <b>gradient</b> (the uphill direction), and each step moves the ball <em>downhill</em>, opposite the gradient. <b>That downhill walk is literally how a neural network trains:</b> the loss surface is the error, and every weight is nudged a little against its gradient until the ball settles in a valley.</p>
</div>
<div class="nar-card">
<h3>2 · Integration <span style="color:var(--muted);font-weight:400;">→ probability as area</span></h3>
<p>Integration is just <b>adding up area under a curve</b>. The demo fills the region with rectangles (a Riemann sum) and shows the sum closing in on the exact area as you add more rectangles. Why ML cares: the area under a probability density between two points <em>is</em> the probability of landing there, and the softmax denominator is exactly this kind of normalizing sum. Area = probability is the whole idea.</p>
</div>
<div class="nar-card">
<h3>3 · Linear Algebra <span style="color:var(--muted);font-weight:400;">→ the language of every layer</span></h3>
<p>Drag two vectors and watch their <b>dot product</b> and the angle between them. The dot product measures alignment — it is large when vectors point the same way, zero when perpendicular. That single number is what an attention head computes between a query and a key, and what cosine similarity uses to compare embeddings. The matrix demo shows how a 2×2 matrix <em>transforms</em> space, and its <b>eigenvectors</b> (the directions that only stretch, never rotate) — the same idea PCA uses to find the axes your data actually varies along.</p>
</div>
<div class="nar-card">
<h3>4 · Probability <span style="color:var(--muted);font-weight:400;">→ uncertainty & sampling</span></h3>
<p>Reshape a distribution with sliders, then draw samples and watch them pile up under the curve. The second demo shows the <b>Law of Large Numbers</b>: as you draw more samples, their running average homes in on the true mean. This is why training on bigger batches gives more stable gradient estimates, and why a sampled metric over more examples is more trustworthy.</p>
</div>
<div class="nar-card">
<h3>5 · Statistics <span style="color:var(--muted);font-weight:400;">→ understanding data & curves</span></h3>
<p>Drop points on a scatter plot and watch the mean, spread (<b>variance / standard deviation</b>), and <b>correlation</b> update live. Correlation near ±1 means a tight line; near 0 means no linear relationship. The second demo is the <b>Central Limit Theorem</b>: take averages of any messy distribution and their histogram becomes a bell curve. This is the reason confidence intervals and so many statistical tests work at all.</p>
</div>
<div class="nar-card">
<h3>6 · ML Metrics <span style="color:var(--muted);font-weight:400;">→ judging a model honestly</span></h3>
<p>Slide the decision <b>threshold</b> and watch the confusion matrix and precision/recall/F1 react. Push the threshold up and you catch fewer positives but make fewer false alarms — the core tradeoff. The <b>ROC curve</b> sweeps every threshold at once; its area (<b>AUC</b>) summarizes ranking quality in one number. This is why "95% accuracy" can be meaningless on imbalanced data, and what to report instead.</p>
</div>
<div class="nar-tip nar-card" style="background:rgba(108,99,255,0.05);">
Ready to play? Open the <a href="#" onclick="window.LessonTabs&&window.LessonTabs.activate('mathlab','lab');return false;"><b>Interactive Lab</b></a> tab and use the left sidebar to jump between the six topics. Every control is live and reacts instantly.
</div>
</div>
<!-- ── PANEL 3: WORKED EXAMPLES (hand computations) ── -->
<div id="np-worked" class="lesson-narrative" data-tab-panel="worked" hidden>
<div class="nar-h2">Worked Examples — by hand, then in the demo</div>
<div class="nar-intro">Numbers make it stick. Here are three short computations done fully by hand, each pointing at the demo that shows the same thing live. Grab a pen if you like — every step is spelled out.</div>
<div class="worked-box">
<div class="worked-label">Worked example 1 · a derivative</div>
<h3>What is the slope of f(x) = x² at x = 3?</h3>
<p>The derivative of <code>x²</code> is <code>f′(x) = 2x</code> (power rule: bring the exponent down, subtract one). Evaluate at x = 3:</p>
<div class="worked-step">f(x) = x²<br>f′(x) = 2x <span class="cmt"># power rule</span><br>f′(3) = 2 · 3 = <span class="res">6</span></div>
<p>So at x = 3 the curve rises 6 units for every 1 unit you move right — a fairly steep slope. Sanity-check it from first principles with a tiny step h = 0.001:</p>
<div class="worked-step">[f(3+h) − f(3)] / h<br>= [(3.001)² − 3²] / 0.001<br>= [9.006001 − 9] / 0.001<br>= 0.006001 / 0.001 ≈ <span class="res">6.001</span> ✓ <span class="cmt"># matches 2x = 6</span></div>
<p><b>See it live:</b> in the Lab, open <b>1 · Derivatives</b>, pick the <code>x²</code> curve, and drag the point toward x = 3 — the slope readout will read ≈ 6.</p>
<button class="try-link" onclick="window.LessonTabs&&window.LessonTabs.activate('mathlab','lab');showSection('s1');var s=document.getElementById('deriv-fn');if(s){s.value='quad';if(window.derivDraw)derivDraw();}">Open this demo →</button>
</div>
<div class="worked-box">
<div class="worked-label">Worked example 2 · a gradient + one descent step</div>
<h3>Gradient of L(x, y) = x² + y² at (2, 1), then one step</h3>
<p>The gradient is the vector of partial derivatives — differentiate with respect to each variable, treating the other as a constant:</p>
<div class="worked-step">∂L/∂x = 2x ∂L/∂y = 2y<br>∇L(2, 1) = (2·2, 2·1) = <span class="res">(4, 2)</span></div>
<details style="margin:12px 0;border:1px solid var(--border,#30363d);border-radius:10px;background:var(--surface,#161b22);padding:0 15px;">
<summary style="cursor:pointer;font-weight:700;padding:13px 0;color:var(--accent2,#58d6ff);list-style:none;">Confused by <b>∂L</b> and <b>∇L</b> ("del L")? — what they are, how, why, and where the symbols come from ▾</summary>
<div style="padding:2px 0 16px;line-height:1.7;">
<p><b>Say them out loud.</b> <code>∂L/∂x</code> is "partial L by partial x" (often just "partial"). <code>∇L</code> is "del L" or "nabla L". They are not two rival things — one is a single piece, the other is the whole bundle of pieces.</p>
<p><b>∂ (the "curly d") = one slope.</b> A partial derivative asks: <em>if I nudge just this one variable a tiny bit and hold the others frozen, how fast does the loss change?</em> <code>∂L/∂x = 2x</code> is the slope of the loss in the x-direction alone; there is a separate one for each variable (<code>∂L/∂y = 2y</code>).</p>
<p><b>∇ (del / nabla) = all those slopes, bundled into one arrow.</b> The gradient just collects every partial into a single vector: <code>∇L = (∂L/∂x, ∂L/∂y)</code>, which here is <code>(4, 2)</code>. So "del L" is the list of how steeply the loss rises in each direction — and as one arrow it points in the single <em>steepest-uphill</em> direction.</p>
<p><b>Why it runs every model (the point).</b> ∇L points <em>uphill</em>, toward <em>more</em> loss. We want <em>less</em>, so we step the exact opposite way: <code>w ← w − α·∇L</code>. The minus is "go downhill"; α (the learning rate) is the step size. Repeat and you roll to the bottom of the bowl — that one rule, <em>follow −∇L downhill</em>, is how almost every model is trained.</p>
<p style="color:var(--muted,#8b949e);"><b>A hill in fog.</b> "Slope if I step north" and "slope if I step east" are the two partials; ∇L fuses them into the single compass arrow pointing most steeply uphill. To descend fastest, walk the reverse of that arrow.</p>
<p style="color:var(--muted,#8b949e);font-size:13.5px;border-top:1px solid var(--border,#30363d);padding-top:11px;"><b>Where the symbols come from (you asked).</b> The curly <b>∂</b> is a stylized "d"; used by Legendre and Condorcet in the 1700s and standardized by <b>Jacobi</b> in the 1840s to mark a <em>partial</em> derivative (versus the ordinary <code>d</code>). The <b>∇</b> was introduced by <b>William Rowan Hamilton</b> around 1837 as an operator; it got nicknamed <b>"nabla"</b> after an ancient harp it resembles, while <b>"del"</b> became its spoken name — then <b>Heaviside</b> and <b>Gibbs</b> built modern vector calculus around it in the 1880s. Using the gradient to <em>minimize</em> a function — <b>gradient descent</b> — was proposed by <b>Augustin-Louis Cauchy</b> in <b>1847</b>. So training a network runs a ~175-year-old idea written in ~180-year-old notation.</p>
</div>
</details>
<p>That vector points <em>uphill</em> (toward higher loss). Gradient descent steps the <em>opposite</em> way. With learning rate α = 0.1, one update <code>w ← w − α·∇L</code> gives:</p>
<div class="worked-step">x ← 2 − 0.1 · 4 = <span class="res">1.6</span><br>y ← 1 − 0.1 · 2 = <span class="res">0.8</span><br><span class="cmt"># loss dropped: 2²+1²=5 → 1.6²+0.8²=2.56+0.64=3.20</span></div>
<p>One step cut the loss from 5 to 3.2 — and it will keep shrinking toward 0 at the bowl's center (0, 0).</p>
<p><b>See it live:</b> open <b>1 · Derivatives → Demo 1b</b>, choose the <code>Quadratic Bowl</code>, set α to 0.10, and press <b>Step</b> — the ball moves toward the center and the loss readout falls just like above.</p>
<button class="try-link" onclick="window.LessonTabs&&window.LessonTabs.activate('mathlab','lab');showSection('s1');var s=document.getElementById('gd-surf');if(s){s.value='bowl';}var lr=document.getElementById('gd-lr');if(lr){lr.value='0.1';var lv=document.getElementById('gd-lr-v');if(lv)lv.textContent='0.10';}if(window.gdReset)gdReset();">Open this demo →</button>
</div>
<div class="worked-box">
<div class="worked-label">Worked example 3 · mean & variance</div>
<h3>Mean and variance of the data set {2, 4, 4, 6}</h3>
<p>The mean is the sum divided by the count; the variance is the average squared distance from the mean:</p>
<div class="worked-step">μ = (2 + 4 + 4 + 6) / 4 = 16 / 4 = <span class="res">4</span><br><br>deviations: (2−4), (4−4), (4−4), (6−4) = −2, 0, 0, 2<br>squared: 4, 0, 0, 4<br>σ² = (4 + 0 + 0 + 4) / 4 = 8 / 4 = <span class="res">2</span><br>σ = √2 ≈ <span class="res">1.414</span> <span class="cmt"># standard deviation</span></div>
<p>The standard deviation (≈1.41) is the typical distance of a point from the mean — a plain-English measure of spread.</p>
<p><b>See it live:</b> open <b>5 · Statistics</b> and drag points; the mean crosshair and the σ readouts update with every move, so you can watch variance grow as you spread the cloud out.</p>
<button class="try-link" onclick="window.LessonTabs&&window.LessonTabs.activate('mathlab','lab');showSection('s5');">Open this demo →</button>
</div>
</div>
<!-- ── PANEL 4: LAB stub. The real viz host (#layout) is a SIBLING below; this
stub exists only so the tab can activate. The lessontab:change listener
hides this prose region and reveals #layout when "lab" is active. ── -->
<div id="np-lab" class="lesson-narrative" data-tab-panel="lab" hidden>
<div class="nar-tip">Loading the interactive lab… if the demos do not appear, pick a topic in the sidebar.</div>
</div>
</div>
<!-- LIVE VIZ HOST — SIBLING of the [data-tabs] root above (NOT a descendant),
so lesson-tabs.js never scans the demos' own selects/sliders/buttons. -->
<div id="mobile-sidebar-toggle" onclick="document.getElementById('sidebar').classList.toggle('mobile-open');this.textContent=document.getElementById('sidebar').classList.contains('mobile-open')?'▲ Hide Topics':'☰ Topics'">☰ Topics</div>
<div id="layout">
<div id="sidebar">
<div class="nav-label">Topics</div>
<button class="nav-btn active" onclick="showSection('s1')"><span class="nav-num">1</span>Derivatives & Gradients</button>
<button class="nav-btn" onclick="showSection('s2')"><span class="nav-num">2</span>Integration</button>
<button class="nav-btn" onclick="showSection('s3')"><span class="nav-num">3</span>Linear Algebra</button>
<button class="nav-btn" onclick="showSection('s4')"><span class="nav-num">4</span>Probability</button>
<button class="nav-btn" onclick="showSection('s5')"><span class="nav-num">5</span>Statistics</button>
<button class="nav-btn" onclick="showSection('s6')"><span class="nav-num">6</span>ML Metrics</button>
</div>
<div id="content">
<!-- ========== SECTION 1: DERIVATIVES ========== -->
<div id="s1" class="section active">
<div class="sec-header">
<div class="sec-title">Derivatives & Gradients <span class="tag tag-ml">backprop</span></div>
<div class="sec-sub">A derivative measures the <strong>rate of change</strong> — how much the output changes per unit change in the input. In ML, gradients are derivatives of the loss w.r.t. each weight. Backprop chains these together to train every parameter.</div>
</div>
<div class="explain-box">
<strong>What:</strong> The derivative f′(x) at a point is the slope of the tangent line to f(x) there — how steep the curve is. In 2D the gradient ∇L is a vector pointing in the direction of steepest <em>increase</em> of loss. We step <em>opposite</em> to it to descend.<br>
<strong>Why it matters:</strong> Every weight update in training is <code>w ← w − lr · ∂L/∂w</code>. Without derivatives there is no learning.
</div>
<div class="math-box">
f′(x) = lim<sub>h→0</sub> [f(x+h) − f(x)] / h<br>
Gradient descent: w ← w − α · ∇<sub>w</sub>L(w)
</div>
<!-- Demo 1a: tangent line -->
<div class="demo-card">
<div class="demo-title">Demo 1a — Drag the point, see the tangent line & slope</div>
<canvas id="c-deriv" width="700" height="280"></canvas>
<div class="ctrl-row">
<div class="ctrl-group">
<label>Curve:</label>
<select id="deriv-fn" onchange="derivDraw()">
<option value="sin">sin(x)</option>
<option value="quad">x²</option>
<option value="cubic">x³ − 3x</option>
<option value="exp">eˣ/5</option>
</select>
</div>
<div class="info-pill"><span>x =</span><strong id="d-x">0.00</strong></div>
<div class="info-pill"><span>f(x) =</span><strong id="d-fx">0.00</strong></div>
<div class="info-pill"><span>slope f′(x) =</span><strong id="d-slope">1.00</strong></div>
</div>
</div>
<!-- Demo 1b: 2D loss surface gradient descent -->
<div class="demo-card">
<div class="demo-title">Demo 1b — 2D Loss Surface: gradient arrow + gradient descent ball</div>
<canvas id="c-gd" width="700" height="300"></canvas>
<div class="ctrl-row">
<div class="ctrl-group"><label>Step size α:</label><input type="range" id="gd-lr" min="0.01" max="0.5" step="0.01" value="0.1" oninput="document.getElementById('gd-lr-v').textContent=parseFloat(this.value).toFixed(2)"><span class="val-badge" id="gd-lr-v">0.10</span></div>
<div class="ctrl-group"><label>Surface:</label>
<select id="gd-surf" onchange="gdReset()">
<option value="bowl">Quadratic Bowl</option>
<option value="saddle">Saddle</option>
<option value="valley">Ravine</option>
</select>
</div>
<button class="btn btn-primary" onclick="gdStep()">Step</button>
<button class="btn btn-green" id="gd-play-btn" onclick="gdTogglePlay()">Play</button>
<button class="btn" onclick="gdReset()">Reset</button>
<div class="info-pill"><span>Loss =</span><strong id="gd-loss">—</strong></div>
<div class="info-pill"><span>Steps =</span><strong id="gd-steps">0</strong></div>
</div>
</div>
</div>
<!-- ========== SECTION 2: INTEGRATION ========== -->
<div id="s2" class="section">
<div class="sec-header">
<div class="sec-title">Integration <span class="tag tag-ml">probability</span></div>
<div class="sec-sub">Integration is <strong>accumulation</strong> — the area under a curve. A probability density function (PDF) integrates to 1; P(a ≤ X ≤ b) is the area between a and b. Riemann sums show how discrete rectangles converge to the exact integral.</div>
</div>
<div class="explain-box">
<strong>What:</strong> ∫ f(x) dx from a to b = the signed area between the curve and the x-axis. Riemann sums approximate this with n rectangles — as n→∞ the sum converges to the integral.<br>
<strong>Why it matters:</strong> Every probability is an integral of a PDF. The softmax denominator is a normalising sum (discrete integral). Expected value E[X] = ∫ x·p(x) dx.
</div>
<div class="math-box">
∫<sub>a</sub><sup>b</sup> f(x) dx ≈ Σᵢ f(xᵢ)·Δx (Riemann sum, Δx=(b−a)/n)<br>
P(a ≤ X ≤ b) = ∫<sub>a</sub><sup>b</sup> p(x) dx where ∫<sub>-∞</sub><sup>∞</sup> p(x)dx = 1
</div>
<div class="demo-card">
<div class="demo-title">Demo 2 — Drag bounds a & b, adjust rectangles; watch area converge</div>
<canvas id="c-integ" width="700" height="300"></canvas>
<div class="ctrl-row">
<div class="ctrl-group"><label>Curve:</label>
<select id="integ-fn" onchange="integDraw()">
<option value="sin">sin(x)+1</option>
<option value="gauss">Gaussian PDF</option>
<option value="quad">x²/4</option>
<option value="exp">e^(−x²)</option>
</select>
</div>
<div class="ctrl-group"><label>Rectangles n:</label><input type="range" id="integ-n" min="2" max="200" value="20" oninput="integDraw()"><span class="val-badge" id="integ-n-v">20</span></div>
<div class="ctrl-group"><label>Method:</label>
<select id="integ-method" onchange="integDraw()">
<option value="left">Left</option>
<option value="mid">Midpoint</option>
<option value="right">Right</option>
</select>
</div>
</div>
<div class="info-row">
<div class="info-pill"><span>a =</span><strong id="integ-a-v">—</strong></div>
<div class="info-pill"><span>b =</span><strong id="integ-b-v">—</strong></div>
<div class="info-pill"><span>Riemann sum ≈</span><strong id="integ-sum">—</strong></div>
<div class="info-pill"><span>Exact integral =</span><strong id="integ-exact">—</strong></div>
<div class="info-pill"><span>Error =</span><strong id="integ-err">—</strong></div>
</div>
<div style="margin-top:8px;font-size:11px;color:var(--muted)">Drag the green (a) and orange (b) markers to set bounds. Drag anywhere else to move both.</div>
</div>
</div>
<!-- ========== SECTION 3: LINEAR ALGEBRA ========== -->
<div id="s3" class="section">
<div class="sec-header">
<div class="sec-title">Linear Algebra <span class="tag tag-ml">embeddings</span></div>
<div class="sec-sub">Vectors, dot products, matrix transforms, and eigenvectors are the backbone of every embedding space, attention computation, and weight matrix in ML.</div>
</div>
<div class="explain-box">
<strong>Dot product</strong> u·v = |u||v|cos θ — measures alignment; projection of v onto u direction. Used in attention scores (Q·Kᵀ).<br>
<strong>Matrix transform</strong> Av maps vectors to new positions — the matrix encodes the transformation. Eigenvectors are special: Av = λv — they only scale, never rotate. PCA finds the eigenvectors of the covariance matrix.
</div>
<div class="two-col">
<div class="demo-card">
<div class="demo-title">Demo 3a — Drag vectors u & v: dot product + projection</div>
<canvas id="c-vec" width="340" height="280"></canvas>
<div class="math-box" style="font-size:11px">u·v = ux·vx + uy·vy = |u||v|cos θ</div>
<div class="info-row">
<div class="info-pill"><span>u·v =</span><strong id="vec-dot">—</strong></div>
<div class="info-pill"><span>θ =</span><strong id="vec-angle">—</strong></div>
<div class="info-pill"><span>proj =</span><strong id="vec-proj">—</strong></div>
</div>
</div>
<div class="demo-card">
<div class="demo-title">Demo 3b — 2×2 Matrix transform: drag sliders, see eigenvectors</div>
<canvas id="c-mat" width="340" height="280"></canvas>
<div class="ctrl-row" style="flex-direction:column;align-items:flex-start;gap:6px">
<div class="ctrl-group"><label style="width:40px">a:</label><input type="range" id="ma" min="-2" max="2" step="0.05" value="1.2" oninput="matDraw()"><span class="val-badge" id="ma-v">1.20</span></div>
<div class="ctrl-group"><label style="width:40px">b:</label><input type="range" id="mb" min="-2" max="2" step="0.05" value="0.4" oninput="matDraw()"><span class="val-badge" id="mb-v">0.40</span></div>
<div class="ctrl-group"><label style="width:40px">c:</label><input type="range" id="mc" min="-2" max="2" step="0.05" value="0.3" oninput="matDraw()"><span class="val-badge" id="mc-v">0.30</span></div>
<div class="ctrl-group"><label style="width:40px">d:</label><input type="range" id="md" min="-2" max="2" step="0.05" value="0.8" oninput="matDraw()"><span class="val-badge" id="md-v">0.80</span></div>
</div>
<div class="info-row">
<div class="info-pill"><span>det =</span><strong id="mat-det">—</strong></div>
<div class="info-pill"><span>λ₁ =</span><strong id="mat-e1">—</strong></div>
<div class="info-pill"><span>λ₂ =</span><strong id="mat-e2">—</strong></div>
</div>
</div>
</div>
</div>
<!-- ========== SECTION 4: PROBABILITY ========== -->
<div id="s4" class="section">
<div class="sec-header">
<div class="sec-title">Probability <span class="tag tag-ml">softmax / sampling</span></div>
<div class="sec-sub">Probability distributions describe uncertainty. The normal distribution appears everywhere. Bernoulli/Binomial model coin flips. The Law of Large Numbers says: with enough samples, the empirical mean converges to the true mean — exactly why batch statistics work.</div>
</div>
<div class="explain-box">
<strong>PDF → probability:</strong> area under curve between a and b. <strong>Softmax</strong> converts logits to a categorical distribution. <strong>Sampling:</strong> drawing from a distribution is fundamental to MCMC, variational inference, and temperature-based LLM decoding.
</div>
<div class="demo-card">
<div class="demo-title">Demo 4a — Distribution explorer: reshape with sliders, draw samples</div>
<div style="margin-bottom:10px">
<button class="dist-btn active" onclick="setDist('normal')">Normal</button>
<button class="dist-btn" onclick="setDist('uniform')">Uniform</button>
<button class="dist-btn" onclick="setDist('binomial')">Binomial</button>
<button class="dist-btn" onclick="setDist('exponential')">Exponential</button>
</div>
<canvas id="c-dist" width="700" height="240"></canvas>
<div class="ctrl-row" id="dist-ctrls"></div>
<div class="info-row">
<div class="info-pill"><span>Mean =</span><strong id="dist-mean">—</strong></div>
<div class="info-pill"><span>Variance =</span><strong id="dist-var">—</strong></div>
<div class="info-pill"><span>Samples drawn =</span><strong id="dist-n">0</strong></div>
<button class="btn btn-primary" onclick="distSample(50)">Draw 50 samples</button>
<button class="btn" onclick="distClearSamples()">Clear samples</button>
</div>
</div>
<div class="demo-card">
<div class="demo-title">Demo 4b — Law of Large Numbers: running average → true mean</div>
<canvas id="c-lln" width="700" height="220"></canvas>
<div class="ctrl-row">
<button class="btn btn-primary" onclick="llnStep(1)">+1 sample</button>
<button class="btn btn-green" id="lln-play-btn" onclick="llnToggle()">Play</button>
<button class="btn" onclick="llnReset()">Reset</button>
<div class="ctrl-group"><label>Distribution:</label>
<select id="lln-dist" onchange="llnReset()">
<option value="normal">Normal(0,1)</option>
<option value="uniform">Uniform(0,1)</option>
<option value="exp">Exponential(λ=1)</option>
</select>
</div>
<div class="info-pill"><span>n =</span><strong id="lln-n">0</strong></div>
<div class="info-pill"><span>x̄ =</span><strong id="lln-mean">—</strong></div>
<div class="info-pill"><span>true μ =</span><strong id="lln-true">—</strong></div>
</div>
</div>
</div>
<!-- ========== SECTION 5: STATISTICS ========== -->
<div id="s5" class="section">
<div class="sec-header">
<div class="sec-title">Statistics <span class="tag tag-ml">data understanding</span></div>
<div class="sec-sub">Statistics turns raw numbers into understanding. Mean, variance, and correlation tell you the shape of your data. The Central Limit Theorem (CLT) explains why sample averages tend toward normal as sample size grows, under common finite-variance conditions — the foundation of confidence intervals and hypothesis tests.</div>
</div>
<div class="explain-box">
<strong>Variance</strong> σ² = E[(X−μ)²] measures spread. <strong>Correlation</strong> r ∈ [−1,1] measures linear association — r=0 doesn't mean independence. <strong>CLT:</strong> regardless of the original distribution, the distribution of sample means → Normal as n grows.
</div>
<div class="math-box">
μ = (1/n)Σxᵢ σ² = (1/n)Σ(xᵢ−μ)² r = Σ(xᵢ−x̄)(yᵢ−ȳ) / (n·σ<sub>x</sub>σ<sub>y</sub>)
</div>
<div class="demo-card">
<div class="demo-title">Demo 5a — Drag points: live mean, median, variance, std, correlation r</div>
<canvas id="c-stats" width="700" height="300"></canvas>
<div class="ctrl-row">
<button class="btn btn-primary" onclick="statsAddPoint()">Add random point</button>
<button class="btn" onclick="statsClear()">Clear</button>
<div class="info-pill"><span>n =</span><strong id="st-n">0</strong></div>
<div class="info-pill"><span>x̄ =</span><strong id="st-mx">—</strong></div>
<div class="info-pill"><span>ȳ =</span><strong id="st-my">—</strong></div>
<div class="info-pill"><span>σx =</span><strong id="st-sx">—</strong></div>
<div class="info-pill"><span>σy =</span><strong id="st-sy">—</strong></div>
<div class="info-pill"><span>r =</span><strong id="st-r">—</strong></div>
</div>
<div style="font-size:11px;color:var(--muted);margin-top:6px">Click canvas to add points. Drag existing points.</div>
</div>
<div class="demo-card">
<div class="demo-title">Demo 5b — Central Limit Theorem: histogram of sample means → Normal</div>
<canvas id="c-clt" width="700" height="240"></canvas>
<div class="ctrl-row">
<div class="ctrl-group"><label>Sample size n:</label><input type="range" id="clt-n" min="1" max="50" value="5" oninput="cltNChange()"><span class="val-badge" id="clt-n-v">5</span></div>
<div class="ctrl-group"><label>Population:</label>
<select id="clt-pop" onchange="cltReset()">
<option value="uniform">Uniform</option>
<option value="exp">Exponential</option>
<option value="bimodal">Bimodal</option>
</select>
</div>
<button class="btn btn-primary" onclick="cltStep(200)">+200 samples</button>
<button class="btn btn-green" id="clt-play-btn" onclick="cltToggle()">Play</button>
<button class="btn" onclick="cltReset()">Reset</button>
<div class="info-pill"><span>experiments =</span><strong id="clt-count">0</strong></div>
</div>
</div>
</div>
<!-- ========== SECTION 6: ML METRICS ========== -->
<div id="s6" class="section">
<div class="sec-header">
<div class="sec-title">ML Metrics <span class="tag tag-ml">model eval</span></div>
<div class="sec-sub">Accuracy alone is misleading on imbalanced data. Precision, recall, F1, and AUC-ROC give a fuller picture. The confusion matrix changes with the decision threshold — the ROC curve shows the full tradeoff.</div>
</div>
<div class="explain-box">
<strong>Precision</strong> = TP/(TP+FP) — of predicted positives, how many are real?<br>
<strong>Recall</strong> = TP/(TP+FN) — of real positives, how many did we catch?<br>
<strong>F1</strong> = 2·P·R/(P+R) — harmonic mean, balanced. <strong>ROC AUC</strong> = probability model ranks a random positive above a random negative.
</div>
<div class="math-box">
Accuracy = (TP+TN)/(TP+TN+FP+FN) F1 = 2·Precision·Recall/(Precision+Recall)<br>
ROC: sweep threshold τ → plot (FPR, TPR); AUC = ∫ ROC dFPR
</div>
<div class="demo-card">
<div class="demo-title">Demo 6a — Drag the threshold: confusion matrix + metrics update live</div>
<canvas id="c-conf" width="700" height="260"></canvas>
<div class="ctrl-row">
<div class="ctrl-group"><label>Threshold τ:</label><input type="range" id="conf-thresh" min="0" max="1" step="0.01" value="0.5" oninput="confUpdate()"><span class="val-badge" id="conf-thresh-v">0.50</span></div>
<div class="ctrl-group"><label>Model quality:</label>
<select id="conf-qual" onchange="confGenData()">
<option value="good">Good</option>
<option value="ok">OK</option>
<option value="poor">Poor</option>
<option value="random">Random</option>
</select>
</div>
<button class="btn" onclick="confGenData()">New dataset</button>
</div>
<div class="info-row">
<div class="info-pill"><span>Accuracy =</span><strong id="cm-acc">—</strong></div>
<div class="info-pill"><span>Precision =</span><strong id="cm-prec">—</strong></div>
<div class="info-pill"><span>Recall =</span><strong id="cm-rec">—</strong></div>
<div class="info-pill"><span>F1 =</span><strong id="cm-f1">—</strong></div>
<div class="info-pill"><span>TP=</span><strong id="cm-tp">—</strong> <span>FP=</span><strong id="cm-fp">—</strong> <span>FN=</span><strong id="cm-fn">—</strong> <span>TN=</span><strong id="cm-tn">—</strong></div>
</div>
</div>
<div class="demo-card">
<div class="demo-title">Demo 6b — ROC curve: threshold sweeps to trace the full curve + AUC</div>
<div class="two-col">
<div>
<canvas id="c-roc" width="340" height="280"></canvas>
</div>
<div>
<canvas id="c-losscurve" width="340" height="280"></canvas>
<div class="demo-title" style="margin-top:10px">Loss curves (MSE vs Cross-Entropy): hover to probe</div>
</div>
</div>
<div class="info-row">
<div class="info-pill"><span>AUC =</span><strong id="roc-auc">—</strong></div>
<div class="info-pill"><span>Current TPR =</span><strong id="roc-tpr">—</strong></div>
<div class="info-pill"><span>Current FPR =</span><strong id="roc-fpr">—</strong></div>
</div>
</div>
</div>
</div><!-- end #content -->
</div><!-- end #layout -->
<script>
// ─── UTILITY ───────────────────────────────────────────────────
function showSection(id) {
document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));
document.getElementById(id).classList.add('active');
const idx = parseInt(id.replace('s',''))-1;
document.querySelectorAll('.nav-btn')[idx].classList.add('active');
// init demos on first show
if (id==='s1' && !s1init) initS1();
if (id==='s2' && !s2init) initS2();
if (id==='s3' && !s3init) initS3();
if (id==='s4' && !s4init) initS4();
if (id==='s5' && !s5init) initS5();
if (id==='s6' && !s6init) initS6();
}
function clamp(v,lo,hi){return Math.max(lo,Math.min(hi,v));}
function lerp(a,b,t){return a+(b-a)*t;}
function fmt(v,d=3){return isNaN(v)?'NaN':v.toFixed(d);}
// ─── SECTION 1: DERIVATIVES ────────────────────────────────────
let s1init=false;
let derivX=0, derivDragging=false;
const DERIV_FNS = {
sin: {f: x=>Math.sin(x), df: x=>Math.cos(x), xmin:-Math.PI*1.5, xmax:Math.PI*1.5},
quad: {f: x=>x*x*0.3, df: x=>0.6*x, xmin:-3, xmax:3},
cubic:{f: x=>0.15*(x*x*x-3*x), df: x=>0.15*(3*x*x-3), xmin:-2.5, xmax:2.5},
exp: {f: x=>Math.exp(x)*0.2, df: x=>Math.exp(x)*0.2, xmin:-2, xmax:2},
};
function initS1(){
s1init=true;
const cv=document.getElementById('c-deriv');
derivX=0;
derivDraw();
cv.addEventListener('mousemove',e=>{
if(!derivDragging)return;
const r=cv.getBoundingClientRect();
const fn=DERIV_FNS[document.getElementById('deriv-fn').value];
derivX=lerp(fn.xmin,fn.xmax,(e.clientX-r.left)/cv.width);
derivDraw();
});
cv.addEventListener('mousedown',e=>{
derivDragging=true;
const r=cv.getBoundingClientRect();
const fn=DERIV_FNS[document.getElementById('deriv-fn').value];
derivX=lerp(fn.xmin,fn.xmax,(e.clientX-r.left)/cv.width);
derivDraw();
});
window.addEventListener('mouseup',()=>{derivDragging=false;});
initGD();
}
function derivDraw(){
const cv=document.getElementById('c-deriv');
const ctx=cv.getContext('2d');
const W=cv.width, H=cv.height;
const fnKey=document.getElementById('deriv-fn').value;
const fn=DERIV_FNS[fnKey];
const {xmin,xmax}=fn;
const yScale=H*0.35;
const cx=W/2, cy=H/2;
const toPixX=x=>(x-xmin)/(xmax-xmin)*W;
const toPixY=y=>cy-y*yScale;
ctx.clearRect(0,0,W,H);
ctx.fillStyle='#0a0c12'; ctx.fillRect(0,0,W,H);
// grid
ctx.strokeStyle='#1e2232'; ctx.lineWidth=1;
for(let gx=Math.ceil(xmin);gx<=xmax;gx++){
ctx.beginPath(); ctx.moveTo(toPixX(gx),0); ctx.lineTo(toPixX(gx),H); ctx.stroke();
}
for(let gy=-3;gy<=3;gy++){
ctx.beginPath(); ctx.moveTo(0,toPixY(gy)); ctx.lineTo(W,toPixY(gy)); ctx.stroke();
}
// axes
ctx.strokeStyle='#3a3d50'; ctx.lineWidth=1.5;
ctx.beginPath(); ctx.moveTo(0,toPixY(0)); ctx.lineTo(W,toPixY(0)); ctx.stroke();
ctx.beginPath(); ctx.moveTo(toPixX(0),0); ctx.lineTo(toPixX(0),H); ctx.stroke();
// curve
ctx.beginPath(); ctx.strokeStyle='#6c63ff'; ctx.lineWidth=2.5;
for(let i=0;i<=W;i++){
const x=lerp(xmin,xmax,i/W);
const y=fn.f(x);
i===0?ctx.moveTo(i,toPixY(y)):ctx.lineTo(i,toPixY(y));
}
ctx.stroke();
// tangent line
const x0=clamp(derivX,xmin,xmax);
const y0=fn.f(x0);
const slope=fn.df(x0);
const tx1=xmin, ty1=y0+slope*(tx1-x0);
const tx2=xmax, ty2=y0+slope*(tx2-x0);
ctx.beginPath(); ctx.strokeStyle='#ffd166'; ctx.lineWidth=1.5; ctx.setLineDash([5,3]);
ctx.moveTo(toPixX(tx1),toPixY(ty1)); ctx.lineTo(toPixX(tx2),toPixY(ty2));
ctx.stroke(); ctx.setLineDash([]);
// point
ctx.beginPath(); ctx.arc(toPixX(x0),toPixY(y0),6,0,Math.PI*2);
ctx.fillStyle='#ff4d6d'; ctx.fill();
ctx.strokeStyle='white'; ctx.lineWidth=1.5; ctx.stroke();
// slope label
ctx.fillStyle='#ffd166'; ctx.font='bold 12px monospace';
ctx.fillText('f\'(x) = '+fmt(slope,3), toPixX(x0)+10, toPixY(y0)-10);
document.getElementById('d-x').textContent=fmt(x0,3);
document.getElementById('d-fx').textContent=fmt(y0,3);
document.getElementById('d-slope').textContent=fmt(slope,3);
}
// Gradient Descent
let gdPos={x:1.5,y:1.5}, gdPlaying=false, gdTimer=null, gdStepCount=0;
function gdSurface(x,y,k){
if(k==='bowl') return x*x+y*y;
if(k==='saddle') return x*x-y*y;
if(k==='valley') return x*x*16+y*y;
return x*x+y*y;
}
function gdGrad(x,y,k){
const h=1e-5;
return {
gx:(gdSurface(x+h,y,k)-gdSurface(x-h,y,k))/(2*h),
gy:(gdSurface(x,y+h,k)-gdSurface(x,y-h,k))/(2*h)
};
}
function initGD(){
gdPos={x:1.5,y:1.2}; gdStepCount=0;
const cv=document.getElementById('c-gd');
cv.addEventListener('click',e=>{
const r=cv.getBoundingClientRect();
const W=cv.width,H=cv.height;
gdPos.x=((e.clientX-r.left)/W-0.5)*4;
gdPos.y=((e.clientY-r.top)/H-0.5)*4;
gdStepCount=0;
gdDraw();
});
gdDraw();
}
function gdDraw(){
const cv=document.getElementById('c-gd');
const ctx=cv.getContext('2d');
const W=cv.width,H=cv.height;
const k=document.getElementById('gd-surf').value;
ctx.clearRect(0,0,W,H);
ctx.fillStyle='#0a0c12'; ctx.fillRect(0,0,W,H);
const toPixX=x=>(x/4+0.5)*W;
const toPixY=y=>(y/4+0.5)*H;
// draw contour-like heatmap
const imgd=ctx.createImageData(W,H);
for(let py=0;py<H;py++){
for(let px=0;px<W;px++){
const wx=(px/W-0.5)*4, wy=(py/H-0.5)*4;
let v=gdSurface(wx,wy,k);
const maxV=k==='bowl'?8:k==='valley'?40:8;
const t=clamp(v/maxV,0,1);
const r2=Math.round(lerp(10,80,t));
const g2=Math.round(lerp(12,20,t));
const b2=Math.round(lerp(24,100,t));
const idx=(py*W+px)*4;
imgd.data[idx]=r2; imgd.data[idx+1]=g2; imgd.data[idx+2]=b2; imgd.data[idx+3]=255;
}
}
ctx.putImageData(imgd,0,0);
// contour lines
ctx.strokeStyle='rgba(108,99,255,0.35)'; ctx.lineWidth=1;
const levels=k==='valley'?[1,4,10,20,35]:[0.5,1,2,4,7];
for(const lv of levels){
ctx.beginPath();
let first=true;
for(let angle=0;angle<=Math.PI*2;angle+=0.04){
// approximate contour by marching
let r=0.1, found=false;
for(r=0.05;r<=2.8;r+=0.04){
const wx=r*Math.cos(angle), wy=r*Math.sin(angle);
if(gdSurface(wx,wy,k)>=lv){found=true;break;}
}
if(found){
const wx=r*Math.cos(angle), wy=r*Math.sin(angle);
first?ctx.moveTo(toPixX(wx),toPixY(wy)):ctx.lineTo(toPixX(wx),toPixY(wy));
first=false;
}
}
ctx.closePath(); ctx.stroke();
}
// gradient arrow at current position
const {gx,gy}=gdGrad(gdPos.x,gdPos.y,k);
const len=Math.sqrt(gx*gx+gy*gy)||1;
const arrowLen=60;
const ax=toPixX(gdPos.x), ay=toPixY(gdPos.y);
const ex=ax+(gx/len)*arrowLen, ey=ay+(gy/len)*arrowLen;
ctx.beginPath(); ctx.strokeStyle='#ff4d6d'; ctx.lineWidth=2.5;
ctx.moveTo(ax,ay); ctx.lineTo(ex,ey); ctx.stroke();
// arrowhead
const angle2=Math.atan2(ey-ay,ex-ax);
ctx.beginPath(); ctx.fillStyle='#ff4d6d';
ctx.moveTo(ex,ey);
ctx.lineTo(ex-14*Math.cos(angle2-0.4),ey-14*Math.sin(angle2-0.4));
ctx.lineTo(ex-14*Math.cos(angle2+0.4),ey-14*Math.sin(angle2+0.4));
ctx.closePath(); ctx.fill();
// ball
ctx.beginPath(); ctx.arc(ax,ay,9,0,Math.PI*2);
ctx.fillStyle='#00d4aa'; ctx.fill();
ctx.strokeStyle='white'; ctx.lineWidth=2; ctx.stroke();
const loss=gdSurface(gdPos.x,gdPos.y,k);
document.getElementById('gd-loss').textContent=fmt(loss,4);
document.getElementById('gd-steps').textContent=gdStepCount;
}
function gdStep(){
const lr=parseFloat(document.getElementById('gd-lr').value);
const k=document.getElementById('gd-surf').value;
const {gx,gy}=gdGrad(gdPos.x,gdPos.y,k);
gdPos.x-=lr*gx; gdPos.y-=lr*gy;
gdPos.x=clamp(gdPos.x,-2,2); gdPos.y=clamp(gdPos.y,-2,2);
gdStepCount++;
gdDraw();
}
function gdTogglePlay(){
gdPlaying=!gdPlaying;
document.getElementById('gd-play-btn').textContent=gdPlaying?'Pause':'Play';
document.getElementById('gd-play-btn').className='btn '+(gdPlaying?'':'btn-green');
if(gdPlaying) gdLoop();
}
function gdLoop(){
if(!gdPlaying)return;
gdStep();
requestAnimationFrame(gdLoop);
}
function gdReset(){
if(gdPlaying){gdPlaying=false;document.getElementById('gd-play-btn').textContent='Play';document.getElementById('gd-play-btn').className='btn btn-green';}
gdPos={x:1.5,y:1.2}; gdStepCount=0; gdDraw();
}
// ─── SECTION 2: INTEGRATION ────────────────────────────────────
let s2init=false;
let integA=-1.5, integB=1.5, integDragTarget=null;
const INTEG_FNS={
sin: {
f:x=>Math.sin(x)+1,
F:(a,b)=>(-Math.cos(b)+b)-(-Math.cos(a)+a),
xmin:-Math.PI, xmax:Math.PI, ymax:2.2
},
gauss:{
f:x=>Math.exp(-x*x/2)/Math.sqrt(2*Math.PI),
F:(a,b)=>{
// numerical
let sum=0,n=1000,dx=(b-a)/n;
for(let i=0;i<n;i++){const x=a+(i+0.5)*dx;sum+=Math.exp(-x*x/2)/Math.sqrt(2*Math.PI)*dx;}
return sum;
},
xmin:-3.5, xmax:3.5, ymax:0.45
},
quad:{
f:x=>x*x/4,
F:(a,b)=>b*b*b/12-a*a*a/12,
xmin:-3, xmax:3, ymax:2.5
},
exp:{
f:x=>Math.exp(-x*x),
F:(a,b)=>{
let sum=0,n=1000,dx=(b-a)/n;
for(let i=0;i<n;i++){const x=a+(i+0.5)*dx;sum+=Math.exp(-x*x)*dx;}
return sum;
},
xmin:-3, xmax:3, ymax:1.1
}
};
function initS2(){
s2init=true;
integA=-1.5; integB=1.5;
const cv=document.getElementById('c-integ');
cv.addEventListener('mousedown',e=>{
const fn=INTEG_FNS[document.getElementById('integ-fn').value];
const W=cv.width;
const r=cv.getBoundingClientRect();
const mx=e.clientX-r.left;
const pxA=(integA-fn.xmin)/(fn.xmax-fn.xmin)*W;
const pxB=(integB-fn.xmin)/(fn.xmax-fn.xmin)*W;
if(Math.abs(mx-pxA)<12) integDragTarget='a';
else if(Math.abs(mx-pxB)<12) integDragTarget='b';
else integDragTarget='both';
});
cv.addEventListener('mousemove',e=>{
if(!integDragTarget)return;
const fn=INTEG_FNS[document.getElementById('integ-fn').value];
const W=cv.width;
const r=cv.getBoundingClientRect();