-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplit_lab.html
More file actions
593 lines (552 loc) · 32.3 KB
/
Copy pathsplit_lab.html
File metadata and controls
593 lines (552 loc) · 32.3 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Split Lab — grow a decision tree by choosing the cuts</title>
<link rel="stylesheet" href="lesson-components.css">
<link rel="stylesheet" href="site-polish.css">
<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>
<style>
:root{
--bg:#0d1117; --surface:#161b22; --surface2:#1c2128; --border:#30363d;
--text:#e6edf3; --muted:#8b949e; --accent:#7c83ff; --accent2:#58d6ff;
--green:#39d353; --red:#ff5c5c; --yellow:#ffdb5c; --blue:#58a6ff;
--classA:#58a6ff; --classB:#ff9e64;
}
*{box-sizing:border-box;margin:0;padding:0;}
body{background:var(--bg);color:var(--text);font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:14px;line-height:1.55;min-height:100vh;}
.wrap{max-width:1080px;margin:0 auto;padding:18px 18px 60px;}
h1{font-size:22px;font-weight:800;}
h1 .grad{background:linear-gradient(90deg,var(--accent),var(--accent2));-webkit-background-clip:text;background-clip:text;color:transparent;}
.sub{color:var(--muted);font-size:14px;margin:8px 0 4px;max-width:820px;}
.kicker{color:var(--accent2);font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.09em;margin-bottom:6px;}
.backlink{display:inline-block;margin-bottom:10px;color:var(--accent2);font-size:13px;text-decoration:none;}
.backlink:hover{text-decoration:underline;}
.callout{background:var(--surface);border:1px solid var(--border);border-left:3px solid var(--accent);border-radius:8px;padding:11px 14px;margin:14px 0;font-size:13.5px;}
.callout .lbl{display:block;font-weight:700;color:var(--accent2);font-size:12px;margin-bottom:4px;}
.callout.warn{border-left-color:var(--yellow);} .callout.warn .lbl{color:var(--yellow);}
.callout.good{border-left-color:var(--green);} .callout.good .lbl{color:var(--green);}
.callout a{color:var(--accent2);font-weight:700;}
.panel{background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:16px;margin:12px 0;}
.panel h3{font-size:13px;color:var(--accent2);text-transform:uppercase;letter-spacing:.05em;margin-bottom:10px;}
.grid{display:grid;grid-template-columns:1.15fr .85fr;gap:16px;margin-top:8px;}
@media(max-width:880px){.grid{grid-template-columns:1fr;}}
canvas{display:block;background:var(--bg);border:1px solid var(--border);border-radius:8px;max-width:100%;}
#scatterWrap{position:relative;}
#scatter{touch-action:none;cursor:crosshair;}
.controls{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:10px 0 4px;}
button.act{background:var(--accent);color:#fff;border:0;border-radius:8px;padding:8px 14px;font-weight:700;cursor:pointer;font-size:13.5px;}
button.act:hover{filter:brightness(1.1);} button.act:disabled{opacity:.4;cursor:not-allowed;}
button.ghost{background:var(--surface2);color:var(--text);border:1px solid var(--border);}
button.ghost:hover{border-color:var(--accent);}
button.tog{background:var(--surface2);border:1px solid var(--border);color:var(--muted);border-radius:7px;padding:7px 13px;font-size:13.5px;cursor:pointer;font-family:'SF Mono',monospace;font-weight:700;}
button.tog.on{background:rgba(124,131,255,.18);border-color:var(--accent);color:#d7d9ff;}
.axislbl{font-family:'SF Mono',monospace;font-size:12px;color:var(--muted);}
/* live impurity readout */
.ig{display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin:8px 0;}
.ig .box{background:var(--surface2);border:1px solid var(--border);border-radius:8px;padding:9px 8px;text-align:center;}
.ig .box .k{font-size:10px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;}
.ig .box .v{font-family:'SF Mono',monospace;font-size:20px;font-weight:800;margin-top:2px;}
.ig .box.before .v{color:var(--text);}
.ig .box.after .v{color:var(--accent2);}
.ig .box.gain .v{color:var(--green);}
.ig .box.gain.neg .v{color:var(--muted);}
.frm{font-family:'SF Mono',monospace;font-size:11.5px;color:var(--muted);margin-top:4px;line-height:1.5;word-break:break-word;}
.hint{font-size:12.5px;color:var(--muted);margin-top:6px;}
.hint b{color:var(--yellow);}
/* tree diagram */
#treeWrap{overflow:auto;}
.treenode{font-family:'SF Mono',monospace;font-size:12px;}
.empty{color:var(--muted);font-style:italic;font-size:13px;}
/* accuracy panel */
.acc-row{display:flex;gap:16px;flex-wrap:wrap;margin:6px 0 10px;}
.acc{flex:1;min-width:120px;}
.acc .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;}
.acc .v{font-family:'SF Mono',monospace;font-size:28px;font-weight:800;}
.acc.train .v{color:var(--blue);} .acc.test .v{color:var(--yellow);}
.acc .bar{height:7px;background:var(--surface2);border-radius:4px;margin-top:5px;overflow:hidden;}
.acc .bar>i{display:block;height:100%;border-radius:4px;}
.acc.train .bar>i{background:var(--blue);} .acc.test .bar>i{background:var(--yellow);}
.slider label{font-size:12px;color:var(--muted);font-weight:700;text-transform:uppercase;letter-spacing:.05em;}
.slider .val{font-family:'SF Mono',monospace;color:var(--accent2);font-weight:800;font-size:16px;}
.slider input[type=range]{width:100%;margin-top:8px;accent-color:var(--accent);}
.gapnote{font-size:12.5px;margin-top:8px;padding:8px 11px;border-radius:8px;}
.gapnote.ok{background:rgba(57,211,83,.10);border:1px solid rgba(57,211,83,.3);color:var(--green);}
.gapnote.over{background:rgba(255,92,92,.10);border:1px solid rgba(255,92,92,.3);color:var(--red);}
.legend{display:flex;gap:16px;align-items:center;font-size:12.5px;color:var(--muted);margin:6px 0;flex-wrap:wrap;}
.legend .dot{display:inline-block;width:11px;height:11px;border-radius:50%;margin-right:5px;vertical-align:-1px;}
.mono{font-family:'SF Mono',monospace;}
</style>
</head>
<body>
<div class="wrap">
<a class="backlink" href="index.html">← All lessons</a>
<div class="kicker">Interactive lab · grow a tree, one cut at a time</div>
<h1>Split Lab — <span class="grad">grow a decision tree by choosing the cuts</span></h1>
<p class="sub">A decision tree carves the plane into boxes with <b>axis-aligned cuts</b> — each split is a single "feature < threshold" question. Here you are the algorithm: <b>click a region</b>, pick feature <b>x</b> or <b>y</b>, and <b>drag the threshold</b>. Watch the <b>Gini impurity</b> drop and the <b>information gain</b> update live, then commit the cut and a node appears in the tree. Compare your instinct against the <b>🤖 greedy best split</b>, push the <b>depth slider</b> until test accuracy falls off the overfit cliff, and <b>grow a forest</b> to watch the jagged boundary smooth out.</p>
<div class="callout"><span class="lbl">📓 The one number a tree optimizes — information gain</span>
A group's <b>impurity</b> is how mixed its classes are (<span class="mono">Gini = 1 − Σ pₖ²</span>, 0 = one pure class, 0.5 = a 50/50 two-class mix). A split's <b>information gain</b> = parent impurity − the size-weighted impurity of its two children. The tree greedily picks the cut with the <b>largest gain</b>. That is the whole engine — and below you turn the crank by hand. This lab reinforces <a href="topic_trees_forests.html">Decision Trees & Random Forests</a>.</p>
</div>
<div class="grid">
<!-- LEFT: scatter + grow-by-hand -->
<div class="panel">
<h3>The plane — click a region, then drag a cut</h3>
<div id="scatterWrap"><canvas id="scatter" width="520" height="520"></canvas></div>
<div class="legend">
<span><span class="dot" style="background:var(--classA)"></span>class A</span>
<span><span class="dot" style="background:var(--classB)"></span>class B</span>
<span class="mono" style="margin-left:auto;color:var(--muted)" id="selInfo">click a box to select a node</span>
</div>
<div class="controls">
<span class="axislbl">cut on:</span>
<button class="tog on" id="featX" onclick="setFeat('x')">x (horizontal axis)</button>
<button class="tog" id="featY" onclick="setFeat('y')">y (vertical axis)</button>
</div>
<div class="controls">
<button class="act" id="btnCommit" onclick="commitSplit()" disabled>✓ commit this cut</button>
<button class="act ghost" id="btnBest" onclick="showBest()" disabled>🤖 best split</button>
<button class="act ghost" onclick="resetTree()">↺ reset tree</button>
</div>
<div class="hint" id="dragHint">Tip: click any colored box above to <b>select that node</b>, then drag the dashed line to place a threshold. The readout updates as you drag.</div>
</div>
<!-- RIGHT: live IG + tree -->
<div class="panel">
<h3>Live split score (the selected node)</h3>
<div class="ig">
<div class="box before"><div class="k">Gini before</div><div class="v" id="gBefore">—</div></div>
<div class="box after"><div class="k">Gini after (weighted)</div><div class="v" id="gAfter">—</div></div>
<div class="box gain"><div class="k">Information gain</div><div class="v" id="gGain">—</div></div>
</div>
<div class="frm" id="igFormula">Select a node and drag a threshold to score a candidate split.</div>
<div class="hint" id="bestHint"></div>
<h3 style="margin-top:18px;">Your tree</h3>
<div id="treeWrap"><div class="empty" id="treeEmpty">The whole dataset is one node (the root). Make your first cut to grow it.</div><pre class="treenode" id="treeDiagram" style="display:none;margin:0;"></pre></div>
<div class="frm" id="treeStats" style="margin-top:8px;"></div>
</div>
</div>
<div class="callout good"><span class="lbl">✓ What the grow-by-hand panel teaches</span>
Every cut is <b>horizontal or vertical</b> — a tree can only ask about one feature at a time, so its boundaries are always made of rectangles (no diagonal lines). Picking the cut with the biggest information gain is exactly what <span class="mono">DecisionTreeClassifier</span> does at every node; the <b>🤖 best split</b> button runs that greedy search so you can check your intuition against it.</p>
</div>
<!-- DEPTH / OVERFIT -->
<div class="panel">
<h3>Auto-grown greedy tree — the depth → overfitting cliff</h3>
<p style="color:var(--muted);font-size:13px;margin-bottom:10px;">This panel ignores your hand-built tree and instead grows the <b>full greedy tree</b> to a chosen depth, then scores it on a <b>30% held-out test set</b> (the points the tree never trained on). Slide depth up and watch train accuracy march to 100% while test accuracy stalls and then <em>drops</em> — the boundary on the left turns into a maze of tiny boxes fit to noise.</p>
<div class="grid" style="grid-template-columns:1fr 1fr;">
<div>
<div class="slider">
<label>max depth = <span class="val" id="depthVal">3</span></label>
<input type="range" id="depth" min="1" max="10" step="1" value="3" oninput="onDepth()">
</div>
<div class="acc-row" style="margin-top:14px;">
<div class="acc train"><div class="k">train accuracy</div><div class="v" id="accTrain">—</div><div class="bar"><i id="barTrain"></i></div></div>
<div class="acc test"><div class="k">test accuracy (held-out)</div><div class="v" id="accTest">—</div><div class="bar"><i id="barTest"></i></div></div>
</div>
<div class="gapnote ok" id="gapNote"></div>
</div>
<div>
<canvas id="depthCanvas" width="300" height="300"></canvas>
<div class="legend" style="margin-top:4px;"><span class="mono" style="color:var(--muted)" id="depthLeaves"></span></div>
</div>
</div>
</div>
<!-- FOREST -->
<div class="panel">
<h3>🌲 Grow a forest — variance reduction by voting</h3>
<p style="color:var(--muted);font-size:13px;margin-bottom:10px;">A single deep tree is <b>high-variance</b>: its boundary is jagged and would lurch if the data shifted. A <b>random forest</b> grows many deep trees, each on a different <b>bootstrap resample</b> of the rows, and averages their votes. The averaged boundary (right) is visibly <b>smoother and rounder</b> than the single deep tree (left) — same bias, far less variance.</p>
<div class="controls">
<button class="act" id="btnForest" onclick="growForest()">🌲 grow a forest (vote 15 trees)</button>
<button class="act ghost" onclick="clearForest()">clear</button>
<span class="mono" id="forestMsg" style="font-size:12.5px;color:var(--muted);"></span>
</div>
<div class="grid" style="grid-template-columns:1fr 1fr;margin-top:6px;">
<div>
<div class="axislbl" style="margin-bottom:5px;">one deep tree (depth 10) — jagged</div>
<canvas id="oneCanvas" width="300" height="300"></canvas>
<div class="frm" id="oneStats" style="margin-top:4px;"></div>
</div>
<div>
<div class="axislbl" style="margin-bottom:5px;">forest of 15 trees — smoothed vote</div>
<canvas id="forestCanvas" width="300" height="300"></canvas>
<div class="frm" id="forestStats" style="margin-top:4px;"></div>
</div>
</div>
<div class="callout" style="margin-top:14px;"><span class="lbl">🧠 Why averaging wins</span> Each tree overfits its own resample in a <em>different</em> direction, so their mistakes point every which way. Average them and the random errors cancel while the shared signal survives — that is <b>bagging</b>. The forest's held-out accuracy is usually as good as or better than the single deep tree, but with a boundary that no longer chases individual noisy points.</p>
</div>
<div class="callout"><span class="lbl">↩ Back to the lesson</span> This lab is the hands-on companion to <a href="topic_trees_forests.html">Decision Trees & Random Forests</a> — Gini/entropy, information gain, greedy recursive axis-aligned splitting, depth → overfitting, and bagging. For the math worked by hand, open that lesson's <b>Math</b> lens.</p>
</div>
<script>
/* ============================================================
Split Lab — vanilla JS, fully offline. All strings are
double-quoted or template literals; typographic apostrophes
are U+2019. No backslash-apostrophe anywhere.
============================================================ */
/* ---------- seeded RNG (reproducible) ---------- */
function lcg(seed){ let s=seed>>>0; return function(){ s=(Math.imul(1103515245,s)+12345)>>>0; return s/4294967296; }; }
/* ---------- the dataset: two features in [0,1], two classes ----------
Pattern: class B sits in two opposite corners (lower-left + upper-right),
class A in the other two — an XOR-ish layout. Axis-aligned trees need a
few cuts (depth >= 2) to separate it, deep trees can overfit the jitter,
and a forest visibly smooths the boundary. ~52 points. */
function makeData(seed){
const rng=lcg(seed), pts=[];
const n=52;
for(let i=0;i<n;i++){
const x=rng(), y=rng();
// base rule: XOR over the midlines
const left=x<0.5, bottom=y<0.5;
let cls=(left===bottom)?1:0; // 1 = class B (corners LL & UR), 0 = class A
// a little label noise near the boundary so deep trees can overfit
const dx=Math.abs(x-0.5), dy=Math.abs(y-0.5);
if(Math.min(dx,dy)<0.10 && rng()<0.30) cls=1-cls;
pts.push({x:x,y:y,c:cls});
}
return pts;
}
const DATA=makeData(20260619);
/* deterministic 70/30 train/test split (every 10th-ish point held out) */
const TRAIN=[], TEST=[];
DATA.forEach((p,i)=>{ (i%10<7?TRAIN:TEST).push(p); });
/* ---------- impurity math (Gini) ---------- */
function counts(pts){ let a=0,b=0; for(const p of pts){ if(p.c===0)a++; else b++; } return [a,b]; }
function gini(pts){
const n=pts.length; if(!n) return 0;
const [a,b]=counts(pts); const pa=a/n, pb=b/n;
return 1-(pa*pa+pb*pb);
}
function majority(pts){ const [a,b]=counts(pts); return b>a?1:0; }
/* weighted child impurity + information gain for a split of `pts` on feature/threshold */
function evalSplit(pts, feat, thr){
const L=[], R=[];
for(const p of pts){ (p[feat]<thr?L:R).push(p); }
const n=pts.length||1;
const gParent=gini(pts);
const gChild=(L.length/n)*gini(L)+(R.length/n)*gini(R);
return { L:L, R:R, gParent:gParent, gChild:gChild, gain:gParent-gChild };
}
/* greedy best split over both features, midpoints between sorted unique values */
function bestSplit(pts){
let best=null;
for(const feat of ["x","y"]){
const vals=pts.map(p=>p[feat]).sort((a,b)=>a-b);
for(let i=0;i<vals.length-1;i++){
if(vals[i+1]===vals[i]) continue;
const thr=(vals[i]+vals[i+1])/2;
const e=evalSplit(pts,feat,thr);
if(e.L.length===0||e.R.length===0) continue;
if(!best || e.gain>best.gain){ best={feat:feat, thr:thr, gain:e.gain, gParent:e.gParent, gChild:e.gChild}; }
}
}
return best;
}
/* ---------- the hand-grown tree ----------
node = {x0,x1,y0,y1, pts, feat,thr, left,right, leaf:bool, id}
bounds are in data space [0,1]^2. */
let NODE_ID=0;
function leafNode(x0,x1,y0,y1,pts){ return {x0:x0,x1:x1,y0:y0,y1:y1,pts:pts,leaf:true,left:null,right:null,feat:null,thr:null,id:NODE_ID++}; }
let TREE, selected=null, curFeat="x", dragThr=null, dragging=false;
function resetTree(){
NODE_ID=0;
TREE=leafNode(0,1,0,1,DATA.slice());
selected=null; dragThr=null; curFeat="x"; setFeat("x");
drawScatter(); renderTree(); renderIG();
document.getElementById("selInfo").textContent="click a box to select a node";
document.getElementById("btnCommit").disabled=true;
document.getElementById("btnBest").disabled=true;
document.getElementById("bestHint").textContent="";
}
/* collect leaves (the visible boxes) */
function leaves(node, out){ out=out||[]; if(node.leaf){ out.push(node); } else { leaves(node.left,out); leaves(node.right,out); } return out; }
/* ---------- scatter rendering ---------- */
const SC=document.getElementById("scatter"), sctx=SC.getContext("2d");
const PAD=34, W=SC.width-PAD-14, H=SC.height-PAD-14;
function dx2px(x){ return PAD + x*W; }
function dy2px(y){ return PAD+H - y*H; } // y up
function px2dx(px){ return (px-PAD)/W; }
function px2dy(py){ return (PAD+H-py)/H; }
const COL=["#58a6ff","#ff9e64"]; // A, B
const FILL=["rgba(88,166,255,0.16)","rgba(255,158,100,0.16)"];
function drawScatter(){
sctx.clearRect(0,0,SC.width,SC.height);
// fill each leaf box by majority class
const lv=leaves(TREE);
lv.forEach(nd=>{
const X=dx2px(nd.x0), Yt=dy2px(nd.y1), bw=(nd.x1-nd.x0)*W, bh=(nd.y1-nd.y0)*H;
if(nd.pts.length){ sctx.fillStyle=FILL[majority(nd.pts)]; sctx.fillRect(X,Yt,bw,bh); }
sctx.strokeStyle="#30363d"; sctx.lineWidth=1; sctx.strokeRect(X,Yt,bw,bh);
});
// highlight selected node
if(selected){
const X=dx2px(selected.x0), Yt=dy2px(selected.y1), bw=(selected.x1-selected.x0)*W, bh=(selected.y1-selected.y0)*H;
sctx.strokeStyle="#7c83ff"; sctx.lineWidth=2.5; sctx.strokeRect(X+1,Yt+1,bw-2,bh-2);
// candidate drag line
if(dragThr!=null){
sctx.save(); sctx.strokeStyle="#ffdb5c"; sctx.lineWidth=2; sctx.setLineDash([6,4]); sctx.beginPath();
if(curFeat==="x"){ const px=dx2px(dragThr); sctx.moveTo(px,Yt); sctx.lineTo(px,Yt+bh); }
else { const py=dy2px(dragThr); sctx.moveTo(X,py); sctx.lineTo(X+bw,py); }
sctx.stroke(); sctx.restore();
}
}
// axis frame + labels
sctx.strokeStyle="#484f58"; sctx.lineWidth=1; sctx.strokeRect(PAD,dy2px(1),W,H);
sctx.fillStyle="#8b949e"; sctx.font="11px sans-serif"; sctx.textAlign="center";
sctx.fillText("feature x →", PAD+W/2, SC.height-8);
sctx.save(); sctx.translate(12,dy2px(1)+H/2); sctx.rotate(-Math.PI/2); sctx.fillText("feature y →",0,0); sctx.restore();
// points
DATA.forEach(p=>{
sctx.beginPath(); sctx.arc(dx2px(p.x), dy2px(p.y), 4.5, 0, 2*Math.PI);
sctx.fillStyle=COL[p.c]; sctx.fill();
sctx.strokeStyle="rgba(13,17,23,0.8)"; sctx.lineWidth=1; sctx.stroke();
});
}
/* find which leaf a click landed in (data coords) */
function leafAt(x,y){ return leaves(TREE).find(nd=> x>=nd.x0 && x<=nd.x1 && y>=nd.y0 && y<=nd.y1); }
/* ---------- pointer interaction ---------- */
function localXY(ev){
const r=SC.getBoundingClientRect();
const sx=SC.width/r.width, sy=SC.height/r.height;
const px=(ev.clientX-r.left)*sx, py=(ev.clientY-r.top)*sy;
return {px:px,py:py,x:px2dx(px),y:px2dy(py)};
}
function clamp(v,lo,hi){ return Math.max(lo,Math.min(hi,v)); }
SC.addEventListener("pointerdown", ev=>{
const q=localXY(ev);
const nd=leafAt(clamp(q.x,0,1),clamp(q.y,0,1));
if(!nd) return;
selected=nd; dragging=true; SC.setPointerCapture(ev.pointerId);
updateDragFromPointer(q);
});
SC.addEventListener("pointermove", ev=>{ if(!dragging) return; updateDragFromPointer(localXY(ev)); });
SC.addEventListener("pointerup", ev=>{ dragging=false; });
SC.addEventListener("pointercancel", ()=>{ dragging=false; });
function updateDragFromPointer(q){
if(!selected) return;
if(curFeat==="x"){ dragThr=clamp(q.x, selected.x0+1e-4, selected.x1-1e-4); }
else { dragThr=clamp(q.y, selected.y0+1e-4, selected.y1-1e-4); }
document.getElementById("selInfo").textContent="node selected · "+selected.pts.length+" points";
drawScatter(); renderIG();
}
function setFeat(f){
curFeat=f;
document.getElementById("featX").classList.toggle("on", f==="x");
document.getElementById("featY").classList.toggle("on", f==="y");
// re-center the candidate line in the selected node when switching axes
if(selected){ dragThr = f==="x" ? (selected.x0+selected.x1)/2 : (selected.y0+selected.y1)/2; }
drawScatter(); renderIG();
}
/* ---------- live IG readout ---------- */
function renderIG(){
const gB=document.getElementById("gBefore"), gA=document.getElementById("gAfter"), gG=document.getElementById("gGain");
const frm=document.getElementById("igFormula"), gainBox=document.querySelector(".ig .box.gain");
if(!selected || dragThr==null){
gB.textContent="—"; gA.textContent="—"; gG.textContent="—"; gainBox.classList.remove("neg");
document.getElementById("btnCommit").disabled=true;
frm.textContent="Select a node and drag a threshold to score a candidate split.";
return;
}
const e=evalSplit(selected.pts, curFeat, dragThr);
gB.textContent=e.gParent.toFixed(3);
gA.textContent=e.gChild.toFixed(3);
gG.textContent=(e.gain>=0?"+":"")+e.gain.toFixed(3);
gainBox.classList.toggle("neg", e.gain<=1e-6);
const [pa,pb]=counts(selected.pts);
const [la,lb]=counts(e.L), [ra,rb]=counts(e.R);
const n=selected.pts.length;
frm.innerHTML =
"Gini(parent) = 1 − (("+pa+"/"+n+")² + ("+pb+"/"+n+")²) = <b>"+e.gParent.toFixed(3)+"</b><br>"+
"split "+curFeat+" < "+dragThr.toFixed(2)+" → left ["+la+"A,"+lb+"B] n="+e.L.length+" · right ["+ra+"A,"+rb+"B] n="+e.R.length+"<br>"+
"Gini(after) = ("+e.L.length+"/"+n+")·"+gini(e.L).toFixed(3)+" + ("+e.R.length+"/"+n+")·"+gini(e.R).toFixed(3)+" = <b>"+e.gChild.toFixed(3)+"</b><br>"+
"<span style='color:var(--green)'>gain = "+e.gParent.toFixed(3)+" − "+e.gChild.toFixed(3)+" = "+(e.gain>=0?"+":"")+e.gain.toFixed(3)+"</span>";
document.getElementById("btnCommit").disabled = (e.L.length===0 || e.R.length===0);
document.getElementById("btnBest").disabled = (selected.pts.length<2);
}
/* ---------- commit a split ---------- */
function commitSplit(){
if(!selected || dragThr==null) return;
const e=evalSplit(selected.pts, curFeat, dragThr);
if(e.L.length===0 || e.R.length===0) return;
const nd=selected, f=curFeat, thr=dragThr;
nd.leaf=false; nd.feat=f; nd.thr=thr;
if(f==="x"){
nd.left =leafNode(nd.x0, thr, nd.y0, nd.y1, e.L); // x < thr
nd.right=leafNode(thr, nd.x1, nd.y0, nd.y1, e.R);
} else {
nd.left =leafNode(nd.x0, nd.x1, nd.y0, thr, e.L); // y < thr
nd.right=leafNode(nd.x0, nd.x1, thr, nd.y1, e.R);
}
selected=null; dragThr=null;
document.getElementById("selInfo").textContent="committed · click another box to keep growing";
document.getElementById("btnCommit").disabled=true;
document.getElementById("btnBest").disabled=true;
document.getElementById("bestHint").textContent="";
drawScatter(); renderTree(); renderIG();
}
/* ---------- 🤖 best split ---------- */
function showBest(){
if(!selected) return;
const b=bestSplit(selected.pts);
if(!b){ document.getElementById("bestHint").textContent="This node cannot be split further."; return; }
setFeat(b.feat); dragThr=b.thr;
drawScatter(); renderIG();
const yourGain = "the dashed line is now on the greedy optimum";
document.getElementById("bestHint").innerHTML="<b>🤖 Greedy best:</b> cut <span class='mono'>"+b.feat+" < "+b.thr.toFixed(2)+"</span> for gain <span class='mono' style='color:var(--green)'>+"+b.gain.toFixed(3)+"</span>. That is the highest-gain cut for this node — commit it, or drag away to compare.";
}
/* ---------- tree diagram (text) ---------- */
function renderTree(){
const lv=leaves(TREE);
const empty=document.getElementById("treeEmpty"), pre=document.getElementById("treeDiagram");
if(lv.length<=1 && TREE.leaf){
empty.style.display="block"; pre.style.display="none";
document.getElementById("treeStats").textContent="";
return;
}
empty.style.display="none"; pre.style.display="block";
let out="";
function walk(nd, prefix, isLast, isRoot){
if(isRoot){
if(nd.leaf){ out+="root → leaf\n"; return; }
out+="root: "+nd.feat+" < "+nd.thr.toFixed(2)+"?\n";
walk(nd.left, "", false, false);
walk(nd.right, "", true, false);
return;
}
const branch=isLast?"└─ ":"├─ ";
if(nd.leaf){
const [a,b]=counts(nd.pts); const cls=majority(nd.pts);
const label=cls===0?"A":"B";
const colored="<span style='color:"+COL[cls]+";font-weight:700'>predict "+label+"</span>";
out+=prefix+branch+colored+" ["+a+"A,"+b+"B]\n";
} else {
out+=prefix+branch+"<span style='color:var(--accent2)'>"+nd.feat+" < "+nd.thr.toFixed(2)+"?</span>\n";
const np=prefix+(isLast?" ":"│ ");
walk(nd.left, np, false, false);
walk(nd.right, np, true, false);
}
}
// header row showing < / >= convention
walk(TREE, "", true, true);
pre.innerHTML=out;
// train/test accuracy of the hand-built tree
const trA=accuracyOf(TREE, TRAIN), teA=accuracyOf(TREE, TEST);
document.getElementById("treeStats").innerHTML =
lv.length+" leaves · left branch = feature < threshold, right = ≥ · "+
"hand-tree accuracy: train <b style='color:var(--blue)'>"+(trA*100).toFixed(0)+"%</b> / test <b style='color:var(--yellow)'>"+(teA*100).toFixed(0)+"%</b>";
}
/* predict a point with a built tree (manual TREE structure) */
function predictManual(node, p){
let nd=node;
while(!nd.leaf){ nd = (p[nd.feat]<nd.thr) ? nd.left : nd.right; }
return majority(nd.pts.length?nd.pts:[ {c:0} ]);
}
function accuracyOf(node, set){
if(!set.length) return 0;
let ok=0; for(const p of set){ if(predictManual(node,p)===p.c) ok++; }
return ok/set.length;
}
/* ============================================================
AUTO-GROWN GREEDY TREE (depth slider + forest). Independent
of the hand-built TREE. Trees are trained on a given set of
points to a max depth via the same greedy gain.
============================================================ */
function growGreedy(pts, depth, maxDepth){
// returns {leaf, pred} or {feat,thr,left,right}
const [a,b]=counts(pts);
if(depth>=maxDepth || a===0 || b===0 || pts.length<2){
return { leaf:true, pred: b>a?1:0, n:pts.length };
}
const bs=bestSplit(pts);
if(!bs || bs.gain<=1e-9){ return { leaf:true, pred: b>a?1:0, n:pts.length }; }
const L=[],R=[];
for(const p of pts){ (p[bs.feat]<bs.thr?L:R).push(p); }
return { leaf:false, feat:bs.feat, thr:bs.thr,
left:growGreedy(L,depth+1,maxDepth), right:growGreedy(R,depth+1,maxDepth) };
}
function predictGreedy(node, p){
let nd=node;
while(!nd.leaf){ nd=(p[nd.feat]<nd.thr)?nd.left:nd.right; }
return nd.pred;
}
function countLeaves(node){ return node.leaf?1:countLeaves(node.left)+countLeaves(node.right); }
function accGreedy(node,set){ if(!set.length) return 0; let ok=0; for(const p of set){ if(predictGreedy(node,p)===p.c) ok++; } return ok/set.length; }
/* render a boundary grid for any predict function */
function drawBoundary(canvas, predictFn, opts){
opts=opts||{};
const ctx=canvas.getContext("2d"), w=canvas.width, h=canvas.height;
ctx.clearRect(0,0,w,h);
const G= opts.res || 60, cw=w/G, ch=h/G;
for(let i=0;i<G;i++){ for(let j=0;j<G;j++){
const x=(i+0.5)/G, y=(j+0.5)/G;
const v=predictFn(x,y); // 0..1 (prob of B) for forest, else 0/1
// blend between class A and B colors by v
const r=Math.round(88+(255-88)*v), g=Math.round(166+(158-166)*v), bl=Math.round(255+(100-255)*v);
ctx.fillStyle="rgba("+r+","+g+","+bl+","+(opts.alpha||0.30)+")";
ctx.fillRect(i*cw, h-(j+1)*ch, cw+1, ch+1);
}}
// points (train only highlighted)
const drawPts = opts.points || DATA;
drawPts.forEach(p=>{
ctx.beginPath(); ctx.arc(p.x*w, h-p.y*h, 3.4, 0, 2*Math.PI);
ctx.fillStyle=COL[p.c]; ctx.fill(); ctx.strokeStyle="rgba(13,17,23,0.8)"; ctx.lineWidth=0.8; ctx.stroke();
});
ctx.strokeStyle="#484f58"; ctx.lineWidth=1; ctx.strokeRect(0.5,0.5,w-1,h-1);
}
/* ---------- depth slider ---------- */
function onDepth(){
const d=+document.getElementById("depth").value;
document.getElementById("depthVal").textContent=d;
const tree=growGreedy(TRAIN,0,d);
const trA=accGreedy(tree,TRAIN), teA=accGreedy(tree,TEST);
document.getElementById("accTrain").textContent=(trA*100).toFixed(0)+"%";
document.getElementById("accTest").textContent=(teA*100).toFixed(0)+"%";
document.getElementById("barTrain").style.width=(trA*100)+"%";
document.getElementById("barTest").style.width=(teA*100)+"%";
const nl=countLeaves(tree);
document.getElementById("depthLeaves").textContent=nl+" leaves at depth "+d;
drawBoundary(document.getElementById("depthCanvas"), (x,y)=>predictGreedy(tree,{x:x,y:y}), {res:64,alpha:0.34});
const gap=trA-teA;
const note=document.getElementById("gapNote");
if(gap>0.18){ note.className="gapnote over"; note.innerHTML="⚠ <b>Overfit gap "+(gap*100).toFixed(0)+" pts.</b> Train climbed but test fell — the deep tree carved private boxes around noisy points. Notice the maze of tiny tiles on the right."; }
else if(d<=2){ note.className="gapnote ok"; note.innerHTML="Shallow tree: few cuts. Test is close to train, but both may be low — it may be <b>underfitting</b> the corners. Try a bit more depth."; }
else { note.className="gapnote ok"; note.innerHTML="Healthy: train and test are close (gap "+(gap*100).toFixed(0)+" pts). This depth captures the structure without memorizing noise."; }
}
/* ---------- forest (bagging) ---------- */
let FOREST=null;
function bootstrap(pts, rng){ const out=[]; for(let i=0;i<pts.length;i++){ out.push(pts[Math.floor(rng()*pts.length)]); } return out; }
function growForest(){
const rng=lcg(424242);
const N=15, trees=[];
for(let t=0;t<N;t++){ trees.push(growGreedy(bootstrap(TRAIN,rng),0,10)); }
FOREST=trees;
// single deep tree for comparison
const one=growGreedy(TRAIN,0,10);
drawBoundary(document.getElementById("oneCanvas"), (x,y)=>predictGreedy(one,{x:x,y:y}), {res:64,alpha:0.34, points:TRAIN});
// forest: averaged vote -> probability of class B
const fpred=(x,y)=>{ let s=0; for(const tr of trees){ s+=predictGreedy(tr,{x:x,y:y}); } return s/trees.length; };
drawBoundary(document.getElementById("forestCanvas"), fpred, {res:64,alpha:0.34, points:TRAIN});
// accuracies on held-out test
const oneTe=accGreedy(one,TEST);
let fok=0; for(const p of TEST){ const v=fpred(p.x,p.y); if((v>=0.5?1:0)===p.c) fok++; }
const fTe=TEST.length?fok/TEST.length:0;
document.getElementById("oneStats").innerHTML="one deep tree · "+countLeaves(one)+" leaves · test acc <b style='color:var(--yellow)'>"+(oneTe*100).toFixed(0)+"%</b>";
document.getElementById("forestStats").innerHTML="15 bagged trees · averaged vote · test acc <b style='color:var(--yellow)'>"+(fTe*100).toFixed(0)+"%</b>";
document.getElementById("forestMsg").textContent="15 trees grown on bootstrap resamples — boundary is the averaged vote.";
}
function clearForest(){
FOREST=null;
["oneCanvas","forestCanvas"].forEach(id=>{ const c=document.getElementById(id), x=c.getContext("2d"); x.clearRect(0,0,c.width,c.height); x.strokeStyle="#484f58"; x.strokeRect(0.5,0.5,c.width-1,c.height-1); });
document.getElementById("oneStats").textContent=""; document.getElementById("forestStats").textContent="";
document.getElementById("forestMsg").textContent="";
}
/* ---------- init ---------- */
(function(){
resetTree();
onDepth();
clearForest();
})();
</script>
</body>
</html>