About: how pages are checked

tests/sims/decisiontree.test.ts

The automated tests for the /simulators/decision-tree simulator. They run the model on its own, outside the browser, and compare it with a reference that doesn't depend on the model being right. They run on every change to the simulator's code.

  1. On all four datasets, at depths 1 to 6, with Gini and entropy, the root split and training accuracy match scikit-learn's DecisionTreeClassifier.
  2. Gini and entropy are 0 for a pure node and largest (0.5 and 1 bit) for an even split, and every leaf respects the minimum size.
// /simulators/decision-tree: a CART classifier grown the way scikit-learn grows one.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { grow, accuracy, leaves, dataset, DATASETS, impurity, type Criterion } from '../../src/lib/sims/decisionTree.ts';

let sklearn = true;
try { execFileSync('python3', ['-c', 'import sklearn'], { stdio: 'ignore' }); } catch { sklearn = false; }

test("on all four datasets, at depths 1 to 6, with Gini and entropy, the root split and training accuracy match scikit-learn's DecisionTreeClassifier", { skip: !sklearn && 'scikit-learn is not installed' }, () => {
	const cases: { ds: string; seed: number; pts: ReturnType<typeof dataset>; crit: Criterion; depth: number; minLeaf: number }[] = [];
	for (const d of DATASETS) for (const seed of [1, 2]) {
		const pts = dataset(d.id, 120, seed);
		for (const crit of ['gini', 'entropy'] as Criterion[]) for (const depth of [1, 2, 3, 4, 6]) for (const minLeaf of [1, 5]) cases.push({ ds: d.id, seed, pts, crit, depth, minLeaf });
	}
	// scikit-learn shuffles features before searching, so equally good splits can come out in either
	// order; collect what it gives over several random states and require the model's answer among them
	const ref = JSON.parse(execFileSync('python3', ['-c', `
import json, sys
from sklearn.tree import DecisionTreeClassifier
out = []
for c in json.loads(sys.stdin.read()):
    X = [[p['x'], p['y']] for p in c['pts']]; y = [p['c'] for p in c['pts']]
    accs, roots = set(), set()
    for rs in range(8):
        m = DecisionTreeClassifier(criterion=c['crit'], max_depth=c['depth'], min_samples_leaf=c['minLeaf'], random_state=rs).fit(X, y)
        accs.add(round(m.score(X, y), 9))
        t = m.tree_
        roots.add('%s %.6f' % ('xy'[t.feature[0]], t.threshold[0]) if t.feature[0] >= 0 else 'leaf')
    out.append({'accs': sorted(accs), 'roots': sorted(roots)})
print(json.dumps(out))
`], { input: JSON.stringify(cases), maxBuffer: 1 << 26 }).toString());
	cases.forEach((c, i) => {
		const tree = grow(c.pts, { maxDepth: c.depth, minLeaf: c.minLeaf, crit: c.crit });
		const tag = `${c.ds} seed ${c.seed} ${c.crit} depth ${c.depth} min leaf ${c.minLeaf}`;
		const root = tree.left ? `${tree.feat} ${tree.t!.toFixed(6)}` : 'leaf';
		assert.ok(ref[i].roots.includes(root), `${tag}: root ${root}, scikit-learn ${ref[i].roots}`);
		assert.ok(ref[i].accs.includes(Math.round(accuracy(tree, c.pts) * 1e9) / 1e9), `${tag}: accuracy ${accuracy(tree, c.pts)}, scikit-learn ${ref[i].accs}`);
	});
});

test('Gini and entropy are 0 for a pure node and largest (0.5 and 1 bit) for an even split, and every leaf respects the minimum size', () => {
	assert.equal(impurity(10, 0, 'gini'), 0);
	assert.equal(impurity(0, 7, 'entropy'), 0);
	assert.equal(impurity(5, 5, 'gini'), 0.5);
	assert.equal(impurity(5, 5, 'entropy'), 1);
	for (const d of DATASETS) for (const minLeaf of [1, 5, 12]) {
		const t = grow(dataset(d.id, 120, 3), { maxDepth: 8, minLeaf, crit: 'gini' });
		for (const l of leaves(t)) assert.ok(l.n >= minLeaf, `${d.id}: a leaf has ${l.n} points, minimum ${minLeaf}`);
	}
});

Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.

Published