import math
import random
import statistics
from fractions import Fraction as Fr
# ---------- A small CART regression tree, a forest and a boosting loop (squared error) ----------
def best_split(X, y, idx, feats, min_leaf):
"""Greedy search: the (feature, threshold) that most lowers the sum of squared errors."""
n = len(idx)
tot, tot2 = sum(y[i] for i in idx), sum(y[i] ** 2 for i in idx)
parent, best = tot2 - tot * tot / n, None
for f in feats:
order = sorted(idx, key=lambda i: X[i][f])
s = s2 = 0.0
for k in range(1, n):
v = y[order[k - 1]]
s, s2 = s + v, s2 + v * v
a, b = X[order[k - 1]][f], X[order[k]][f]
if k < min_leaf or n - k < min_leaf or a == b:
continue
gain = parent - ((s2 - s * s / k) + ((tot2 - s2) - (tot - s) ** 2 / (n - k)))
if best is None or gain > best[0] + 1e-12:
best = (gain, f, (a + b) / 2)
return best
def grow(X, y, idx, depth, max_depth, min_leaf, max_features, rng, imp=None):
mean = sum(y[i] for i in idx) / len(idx)
if depth == max_depth or len(idx) < 2 * min_leaf or all(y[i] == y[idx[0]] for i in idx):
return mean
d = len(X[0])
feats = range(d) if max_features >= d else rng.sample(range(d), max_features)
best = best_split(X, y, idx, feats, min_leaf)
if best is None or best[0] <= 1e-12:
return mean
gain, f, thr = best
if imp is not None:
imp[f] += gain
left = [i for i in idx if X[i][f] <= thr]
right = [i for i in idx if X[i][f] > thr]
return (f, thr, grow(X, y, left, depth + 1, max_depth, min_leaf, max_features, rng, imp),
grow(X, y, right, depth + 1, max_depth, min_leaf, max_features, rng, imp))
def predict(tree, x):
while isinstance(tree, tuple):
tree = tree[2] if x[tree[0]] <= tree[1] else tree[3]
return tree
def fit_tree(X, y, max_depth=10**9, min_leaf=1, max_features=10**9, rng=None, imp=None):
return grow(X, y, list(range(len(X))), 0, max_depth, min_leaf, max_features, rng or random.Random(0), imp)
def fit_forest(X, y, B, max_features, rng, imp=None):
"""B trees on bootstrap samples; returns the trees and each tree's out-of-bag row indices."""
n, trees, oobs = len(X), [], []
for _ in range(B):
boot = [rng.randrange(n) for _ in range(n)]
seen = set(boot)
trees.append(grow(X, y, boot, 0, 10**9, 1, max_features, rng, imp))
oobs.append([i for i in range(n) if i not in seen])
return trees, oobs
def forest_mean(trees, x):
return statistics.fmean(predict(t, x) for t in trees)
def boost(X, y, Xv, yv, lr, rounds, depth):
"""Gradient boosting for squared error: each tree fits the residuals. Returns validation MSE per round."""
F0 = statistics.fmean(y)
F, Fv = [F0] * len(X), [F0] * len(Xv)
curve = [mse(Fv, yv)]
for _ in range(rounds):
tree = fit_tree(X, [t - p for t, p in zip(y, F)], max_depth=depth)
F = [p + lr * predict(tree, x) for p, x in zip(F, X)]
Fv = [p + lr * predict(tree, x) for p, x in zip(Fv, Xv)]
curve.append(mse(Fv, yv))
return curve
def mse(pred, y):
return statistics.fmean((a - b) ** 2 for a, b in zip(pred, y))
def gini(counts):
n = sum(counts)
return 1 - sum(Fr(c, n) ** 2 for c in counts)
def entropy(counts):
n = sum(counts)
return -sum((c / n) * math.log2(c / n) for c in counts if c)
def med(values):
return round(statistics.median(values), 3)
D = 6
def f_lin(x):
return 2 * x[0] + 2 * x[1] + x[2] + x[3] + x[4] + x[5]
def f_irr(x):
return 3 * (x[0] > 0.3) + 2 * math.sin(6 * x[1]) + x[2] * (x[3] > 0)
def make(seed, n, fn, noise):
r = random.Random(seed)
X = [[r.uniform(-1, 1) for _ in range(D)] for _ in range(n)]
return X, [fn(x) + r.gauss(0, noise) for x in X]
def circle(seed, n, flip=0.15):
r = random.Random(seed)
X = [[r.uniform(-1, 1), r.uniform(-1, 1)] for _ in range(n)]
y = [int(a * a + b * b < 0.5) for a, b in X]
return X, [1 - t if r.random() < flip else t for t in y]
def acc(model, X, y):
return statistics.fmean((predict(model, x) >= 0.5) == t for x, t in zip(X, y))
# 1. Splits by hand: Gini and entropy gain
for name, parent, kids in (("5/5 -> (4,1),(1,4)", (5, 5), ((4, 1), (1, 4))),
("6/4 -> (5,0),(1,4)", (6, 4), ((5, 0), (1, 4)))):
n = sum(parent)
g = gini(parent) - sum(Fr(sum(k), n) * gini(k) for k in kids)
e = entropy(parent) - sum(sum(k) / n * entropy(k) for k in kids)
print("1.", name, "gini parent", gini(parent), "child ginis", [str(gini(k)) for k in kids],
"gini gain", g, "entropy gain %.4f" % e)
# 2. Greedy is myopic: on XOR no first split helps, yet two splits are perfect
pts = [(a, b, int(a != b)) for a in (0, 1) for b in (0, 1) for _ in range(5)]
for f in (0, 1):
kids = [[p[2] for p in pts if p[f] == v] for v in (0, 1)]
gain = gini((10, 10)) - Fr(1, 2) * sum(gini((len(k) - sum(k), sum(k))) for k in kids)
print("2. XOR split on feature", f, "gain", gain)
for v in (0, 1): # split on feature 0 anyway, then on feature 1
side = [p for p in pts if p[0] == v]
kids = [[p[2] for p in side if p[1] == w] for w in (0, 1)]
print(" child gini", gini((len(side) - sum(p[2] for p in side), sum(p[2] for p in side))),
"-> grandchildren", [str(gini((len(k) - sum(k), sum(k)))) for k in kids])
# 3. Depth and leaf size on a noisy circle (15% of labels flipped: best possible accuracy 0.85)
print("3. median train and validation accuracy over 20 seeds")
for label, kw in (("depth 1", dict(max_depth=1)), ("depth 2", dict(max_depth=2)), ("depth 4", dict(max_depth=4)),
("depth 8", dict(max_depth=8)), ("no limit", {}), ("leaf >= 10", dict(min_leaf=10)),
("leaf >= 20", dict(min_leaf=20))):
tr, va = [], []
for s in range(20):
X, y = circle(s, 200)
Xv, yv = circle(1000 + s, 2000)
m = fit_tree(X, y, **kw)
tr.append(acc(m, X, y))
va.append(acc(m, Xv, yv))
print(" ", label, med(tr), med(va))
# 4. The variance formula, exactly: rho sigma^2 + (1 - rho) sigma^2 / B
for rho, B in ((Fr(1, 2), 4), (Fr(3, 10), 10)):
total = sum(1 if i == j else rho for i in range(B) for j in range(B)) # 1' Sigma 1, unit variances
print("4. rho", rho, "B", B, "variance of the mean", total / B ** 2, "formula", rho + (1 - rho) / B)
# 5. Real trees: variance over 30 training sets, bagging versus a random forest
R, B = 30, 100
Xt, _ = make(999, 40, f_lin, 0)
truth = [f_lin(x) for x in Xt]
print("5. 30 training sets of 200 rows; variance of the prediction at 40 fixed points (noise variance 1)")
for name, mf in (("bagging (all 6 features)", 6), ("random forest (2 of 6)", 2)):
P = [] # P[s][b][j]: tree b of training set s at test point j
for s in range(R):
X, y = make(s, 200, f_lin, 1.0)
trees, _ = fit_forest(X, y, B, mf, random.Random(10000 + s))
P.append([[predict(t, x) for x in Xt] for t in trees])
J = range(len(Xt))
ens = lambda s, j, k: statistics.fmean(P[s][b][j] for b in range(k))
sigma2 = statistics.fmean(statistics.pvariance([P[s][b][j] for s in range(R)]) for b in range(B) for j in J)
row = {k: statistics.fmean(statistics.pvariance([ens(s, j, k) for s in range(R)]) for j in J) for k in (1, 5, 25, 100)}
rho = (row[100] - sigma2 / B) / (sigma2 * (1 - 1 / B))
bias2 = statistics.fmean((statistics.fmean(ens(s, j, B) for s in range(R)) - truth[j]) ** 2 for j in J)
print(" %s: one-tree variance %.3f, implied rho %.3f, squared bias %.3f" % (name, sigma2, rho, bias2))
print(" trees -> variance:", {k: round(v, 3) for k, v in row.items()},
"| formula:", {k: round(rho * sigma2 + (1 - rho) * sigma2 / k, 3) for k in row},
"| floor rho*sigma2 = %.3f" % (rho * sigma2))
# 6. Out-of-bag: about 36.8% of rows are left out of each bootstrap, and they give a free estimate
print("6a. expected out-of-bag fraction", {n: round((1 - 1 / n) ** n, 4) for n in (10, 100, 1000)}, "limit 1/e = %.4f" % math.exp(-1))
oob_acc, val_acc = [], []
for s in range(20):
X, y = circle(s, 200)
Xv, yv = circle(1000 + s, 2000)
trees, oobs = fit_forest(X, y, 100, 1, random.Random(s))
votes = [[] for _ in X]
for t, oob in zip(trees, oobs):
for i in oob:
votes[i].append(predict(t, X[i]))
oob_acc.append(statistics.fmean((statistics.fmean(v) >= 0.5) == t for v, t in zip(votes, y) if v))
val_acc.append(statistics.fmean((forest_mean(trees, x) >= 0.5) == t for x, t in zip(Xv, yv)))
print("6b. 100-tree forest, 20 datasets: median OOB accuracy %.3f, validation %.3f, median gap %.3f"
% (statistics.median(oob_acc), statistics.median(val_acc), statistics.median(abs(a - b) for a, b in zip(oob_acc, val_acc))))
# 7. Gradient boosting by hand (squared error), exact; then the log-loss gradient by finite differences
xs, ys, eta = [1, 2, 3, 4, 5, 6], [Fr(v) for v in (1, 3, 2, 6, 7, 9)], Fr(1, 2)
F = [sum(ys) / 6] * 6
print("7a. F0 =", F[0], "mse", sum((t - p) ** 2 for t, p in zip(ys, F)) / 6)
for rnd in (1, 2):
res = [t - p for t, p in zip(ys, F)]
best = None
for k in range(1, 6): # stump: split after the k-th point, leaves are the residual means
lm, rm = sum(res[:k]) / k, sum(res[k:]) / (6 - k)
sse = sum((v - lm) ** 2 for v in res[:k]) + sum((v - rm) ** 2 for v in res[k:])
if best is None or sse < best[0]:
best = (sse, k, lm, rm)
_, k, lm, rm = best
F = [p + eta * (lm if i < k else rm) for i, p in enumerate(F)]
print(" round %d: residuals %s, split after x=%d, leaves %s and %s, new F %s, mse %s"
% (rnd, [str(v) for v in res], xs[k - 1], lm, rm, [str(v) for v in F],
sum((t - p) ** 2 for t, p in zip(ys, F)) / 6))
sigmoid = lambda z: 1 / (1 + math.exp(-z))
for y1 in (1, 0):
loss = lambda z: -(y1 * math.log(sigmoid(z)) + (1 - y1) * math.log(1 - sigmoid(z)))
print("7b. y=%d: numerical d(loss)/dF at F=0.7: %.6f, p - y = %.6f"
% (y1, (loss(0.7 + 1e-6) - loss(0.7 - 1e-6)) / 2e-6, sigmoid(0.7) - y1))
# 8. Learning rate, rounds and depth (validation MSE; noise floor 1.0), median of 6 datasets
print("8. best validation MSE, the round it happens at, and MSE after 800 rounds")
for lr, depth in ((1.0, 1), (0.1, 1), (0.01, 1), (0.1, 3)):
curves = []
for s in range(6):
X, y = make(s, 200, f_lin, 1.0)
Xv, yv = make(500 + s, 1000, f_lin, 1.0)
curves.append(boost(X, y, Xv, yv, lr, 800, depth))
print(" lr %-4s depth %d: best %.3f at round %s, after 800 rounds %.3f"
% (lr, depth, statistics.median(min(c) for c in curves), statistics.median(c.index(min(c)) for c in curves),
statistics.median(c[-1] for c in curves)))
# 9. Which model, on which data? Validation MSE, median of 6 datasets of 200 rows
def ols(X, y):
A = [[1.0] + x for x in X]
k = len(A[0])
M = [[sum(r[i] * r[j] for r in A) for j in range(k)] + [sum(r[i] * t for r, t in zip(A, y))] for i in range(k)]
for c in range(k):
p = max(range(c, k), key=lambda i: abs(M[i][c]))
M[c], M[p] = M[p], M[c]
for i in range(k):
if i != c:
m = M[i][c] / M[c][c]
M[i] = [a - m * b for a, b in zip(M[i], M[c])]
return [M[i][k] / M[i][i] for i in range(k)]
for label, fn, noise in (("linear truth, noise 1.0 (floor 1.0)", f_lin, 1.0),
("steps and a sine, noise 0.5 (floor 0.25)", f_irr, 0.5)):
out = {}
for s in range(6):
X, y = make(s, 200, fn, noise)
Xv, yv = make(500 + s, 1000, fn, noise)
w = ols(X, y)
out.setdefault("linear", []).append(mse([w[0] + sum(a * b for a, b in zip(w[1:], x)) for x in Xv], yv))
out.setdefault("one deep tree", []).append(mse([predict(fit_tree(X, y), x) for x in Xv], yv))
for name, mf in (("bagged trees", 6), ("forest, 2 of 6", 2)):
trees, _ = fit_forest(X, y, 50, mf, random.Random(s))
out.setdefault(name, []).append(mse([forest_mean(trees, x) for x in Xv], yv))
c = boost(X[:150], y[:150], X[150:], y[150:], 0.1, 300, 3) # pick the rounds on the last 50 rows
out.setdefault("boosting", []).append(boost(X, y, Xv, yv, 0.1, max(c.index(min(c)), 1), 3)[-1])
print("9.", label, {k: med(v) for k, v in out.items()})
# 10. Trees cannot extrapolate
X = [[i / 10] for i in range(101)]
w = ols(X, [2 * v[0] for v in X])
print("10. trained on x in [0, 10] with y = 2x; at x = 15 the tree says", predict(fit_tree(X, [2 * v[0] for v in X]), [15]),
"and the line says", round(w[0] + w[1] * 15, 3))
# 11. Importance: impurity (training) versus permutation (validation), and a correlated copy
def signal_data(seed, n):
r = random.Random(seed)
X, y = [], []
for _ in range(n):
s = r.random() < 0.5
y.append(int(s if r.random() < 0.75 else not s))
X.append([1.0 if s else 0.0, r.random(), r.random()]) # a binary signal and two noise columns
return X, y
def forest_acc(trees, X, y):
return statistics.fmean((forest_mean(trees, x) >= 0.5) == t for x, t in zip(X, y))
def shuffled(X, cols, rng):
perm = list(range(len(X)))
rng.shuffle(perm)
out = [x[:] for x in X]
for k, p in enumerate(perm):
for j in cols:
out[k][j] = X[p][j]
return out
shares, drops, tr_acc, va_acc, alone, copy_a, copy_b, both = [], [], [], [], [], [], [], []
for s in range(20):
X, y = signal_data(s, 300)
Xv, yv = signal_data(100 + s, 1000)
rng, imp = random.Random(s), [0.0] * 3
trees, _ = fit_forest(X, y, 50, 2, random.Random(s), imp)
shares.append([v / sum(imp) for v in imp])
base = forest_acc(trees, Xv, yv)
drops.append([base - forest_acc(trees, shuffled(Xv, [j], rng), yv) for j in range(3)])
tr_acc.append(forest_acc(trees, X, y))
va_acc.append(base)
X4, Xv4 = [x + [x[0]] for x in X], [x + [x[0]] for x in Xv] # add an exact copy of the signal
trees4, _ = fit_forest(X4, y, 50, 2, random.Random(s))
base4 = forest_acc(trees4, Xv4, yv)
copy_a.append(base4 - forest_acc(trees4, shuffled(Xv4, [0], rng), yv))
copy_b.append(base4 - forest_acc(trees4, shuffled(Xv4, [3], rng), yv))
both.append(base4 - forest_acc(trees4, shuffled(Xv4, [0, 3], rng), yv))
alone.append(drops[-1][0])
col = lambda rows: [med(r[j] for r in rows) for j in range(3)]
print("11a. columns: binary signal, noise, noise. Impurity importance share (training):", col(shares))
print(" permutation drop on validation:", col(drops), "| forest train accuracy %.3f, validation %.3f"
% (statistics.median(tr_acc), statistics.median(va_acc)))
print("11b. permuting the signal: alone %.3f; with a copy, the original %.3f and the copy %.3f; both together %.3f"
% tuple(statistics.median(v) for v in (alone, copy_a, copy_b, both)))
# 12. Missing values: let the split choose a side, or fill in the mean
def gaps(seed, n):
r = random.Random(seed)
X, y = [], []
for _ in range(n):
label = int(r.random() < 0.5)
X.append(None if r.random() < (0.4 if label else 0.05) else r.gauss(0.5 * label, 1)) # missingness is a signal
y.append(label)
return X, y
def one_split(X, y, Xv, yv, learn_side):
"""Best one-question model on X; returns validation accuracy. Missing goes left or right, or is mean-filled."""
mean = statistics.fmean(x for x in X if x is not None)
prep = (lambda v: v) if learn_side else (lambda v: mean if v is None else v)
rule = lambda x, thr, left_if_missing, lc: lc if (left_if_missing if x is None else x <= thr) else 1 - lc
cuts = sorted({x for x in X if x is not None})[::5]
options = [(t, m, lc) for t in cuts for m in ((True, False) if learn_side else (True,)) for lc in (0, 1)]
best = max(options, key=lambda o: sum(rule(prep(x), *o) == t for x, t in zip(X, y)))
return statistics.fmean(rule(prep(x), *best) == t for x, t in zip(Xv, yv))
learned, filled = [], []
for s in range(20):
X, y = gaps(s, 500)
Xv, yv = gaps(100 + s, 5000)
learned.append(one_split(X, y, Xv, yv, True))
filled.append(one_split(X, y, Xv, yv, False))
print("12. one-split model, validation accuracy: side learned for missing %.3f, mean-filled %.3f"
% (statistics.median(learned), statistics.median(filled)))