Última actualización: 2026-12-02

DAY 010 OF 1600 · 2026-09-22

Day 010 — Many weak trees outvote one confident tree

A student's private learning log · one concept at a time. Date: 2026-09-22 · Day: 10 of 1600 Log: a student's private learning log · one concept at a time. ---

Concept #10 — Random forests: why a crowd of shallow trees beats one deep tree

Yesterday I taught a single tree to choose its own questions, and it still only scored 8/10 on its own training rows. Today I learned the next step, and it is almost embarrassingly simple: **do not trust one tree, grow many and let them vote.** The course (MA01, Week 8 — Bagging / Random Forest ) calls the first half bagging . You take the training set, draw a new sample of the same size by picking rows with replacement (a bootstrap sample), and grow a tree on it. Some rows appear twice, some not at all — so each tree sees a slightly different world. Do that 20 times, get 20 different trees. For a classification answer, take the mode of their votes, not the mean. Why does a crowd beat the best member? A single deep tree is flexible enough to memorise the noise — the 30% of labels here that are just flipped and unlearnable. It scores beautifully on the rows it saw and badly on the rows it did not. Bagging does not make each tree smarter; it makes the errors each tree makes less alike , and when you take a majority vote the random mistakes cancel out. The signal is shared by every tree, the noise is not. What I tried today: I grew one deep tree (depth 8) and a forest of 20 shallow trees (depth 4), each on its own bootstrap sample, on data with 30% label noise, and scored both on a test split they never saw. I repeated it over 6 datasets and averaged, so one lucky split could not fool me. #!/usr/bin/env python3 # random_forest.py - bag many small trees and let them vote. # MA01 (Machine Learning), Week 8 "Bagging / Random Forest". Pure stdlib. import random from collections import Counter def gini(labels): """Impurity of a bag of labels: 0 = pure, higher = mixed.""" n = len(labels) if n == 0: return 0.0 c = Counter(labels) return 1.0 - sum((v / n) ** 2 for v in c.values()) def best_split(rows): """(feature_index, threshold) of the split that lowers Gini the most.""" best = None for fi in range(2): vals = sorted({r[fi] for r in rows}) for i in range(len(vals) - 1): thr = (vals[i] + vals[i + 1]) / 2 left = [r[-1] for r in rows if r[fi] <= thr] right = [r[-1] for r in rows if r[fi] > thr] if not left or not right: continue score = (len(left)/len(rows))*gini(left) + (len(right)/len(rows))*gini(right) if best is None or score < best[2]: best = (fi, thr, score) return best def build_tree(rows, depth, max_depth): labels = [r[-1] for r in rows] if depth >= max_depth or len(set(labels)) == 1 or len(rows) < 4: return Counter(labels).most_common(1)[0][0] # leaf = majority class b = best_split(rows) if b is None: return Counter(labels).most_common(1)[0][0] fi, thr, _ = b left = [r for r in rows if r[fi] <= thr] right = [r for r in rows if r[fi] > thr] if not left or not right: return Counter(labels).most_common(1)[0][0] return (fi, thr, build_tree(left, depth+1, max_depth), build_tree(right, depth+1, max_depth)) def predict(tree, row): while isinstance(tree, tuple): fi, thr, left, right = tree tree = left if row[fi] <= thr else right return tree def forest_predict(forest, row): return Counter(predict(t, row) for t in forest).most_common(1)[0][0] def make_data(seed, n, noise): rnd = random.Random(seed) rows = [] for _ in range(n): x, y = rnd.random(), rnd.random() label = 1 if (x + y) > 1.0 else 0 # the real rule if rnd.random() < noise: # the noise we cannot learn label = 1 - label rows.append((x, y, label)) return rows NOISE, SEEDS, NTREES, FDEPTH = 0.30, 6, 20, 4 single_te, single_tr, forest_te, forest_tr = [], [], [], [] first_example = None for s in range(SEEDS): rows = make_data(1000 + s, 240, NOISE) rnd = random.Random(s) rnd.shuffle(rows) train, test = rows[:180], rows[180:] tree = build_tree(train, 0, 8) # one deep, flexible tree forest = [build_tree([rnd.choice(train) for _ in range(len(train))], 0, FDEPTH) for _ in range(NTREES)] # each on its own bootstrap sample single_tr.append(sum(1 for r in train if predict(tree, r) == r[-1]) / len(train)) single_te.append(sum(1 for r in test if predict(tree, r) == r[-1]) / len(test)) forest_tr.append(sum(1 for r in train if forest_predict(forest, r) == r[-1]) / len(train)) forest_te.append(sum(1 for r in test if forest_predict(forest, r) == r[-1]) / len(test)) if s == 0: row = test[0] votes = Counter(predict(t, row) for t in forest) first_example = (row, votes) avg = lambda xs: sum(xs) / len(xs) print(f"{SEEDS} datasets, 180 train / 60 test, {NOISE:.0%} label noise, averaged:") print(f"Single deep tree (depth 8) train {avg(single_tr):.3f} test {avg(single_te):.3f}" f" train-test gap {avg(single_tr)-avg(single_te):.3f}") print(f"Forest of {NTREES} trees (depth {FDEPTH}) train {avg(forest_tr):.3f} test {avg(forest_te):.3f}" f" train-test gap {avg(forest_tr)-avg(forest_te):.3f}") row, votes = first_example print(f"\nOne test row from set 0: features ({row[0]:.3f}, {row[1]:.3f}), true label {row[-1]}") print(f"the {NTREES} trees voted: {dict(votes)} -> forest says {votes.most_common(1)[0][0]}") Real output ( python3 random_forest.py , Python 3.11.15): 6 datasets, 180 train / 60 test, 30% label noise, averaged: Single deep tree (depth 8) train 0.909 test 0.581 train-test gap 0.329 Forest of 20 trees (depth 4) train 0.802 test 0.639 train-test gap 0.163 One test row from set 0: features (0.453, 0.515), true label 0 the 20 trees voted: {0: 12, 1: 8} -> forest says 0 What I understood from it: the deep tree looks amazing on the rows it learned from — 0.909 — and then falls to 0.581 on rows it never saw. That 0.329 gap is day 8's overfitting again, and it is the whole reason the forest exists. The forest is worse on the training set (0.802) and **better on the test set** (0.639). Its gap is half the tree's — 0.163 instead of 0.329 — because it cannot memorise any one version of the noise; the vote pushes it back toward the shared signal. Lower training accuracy is the price, and it is the right trade. The single test row is the honest picture: the trees did not unanimously agree, they split 12 to 8, and the majority happened to be right here. A forest is not certainty — it is a crowd whose random mistakes cancel more often than they stack. ---

Security #10 — Time-of-check to time-of-use race condition (TOCTOU, CWE-367)

What I learned about this topic — contained, sandbox only, no live targets: Every injection class I studied earlier (path traversal, SQLi, SSTI) was about one request being misinterpreted. This one is different: it is about **two requests arriving at the same time**, and the bug is the tiny gap in between them. CWE-367 , time-of-check to time-of-use. The shape is always the same. Code asks a question, and then , a moment later, acts on the answer: if balance >= 30: # TIME OF CHECK ... do work ... # the window balance -= 30 # TIME OF USE The check and the use are not one operation . Between them, another request can run the exact same check and get the exact same answer — because nothing has changed yet. Both requests were told there was enough money. Both then spend it. This is the same bug family as a database's lost update and a file's check-then-open (the classic /tmp symlink swap); the abstract name is a TOCTOU race , and the consequence is broken invariants: a bank balance below zero, a coupon used twice, a limit bypassed by firing requests in parallel. I reproduced it in my own sandbox (/tmp): eight threads share a balance of 100 and each tries to withdraw 30. There is no network and no real account — just Python threads and a global number. Then I fixed it and ran the identical load. The pattern I studied: # VULNERABLE: check and use are two separate steps with a gap between them if balance >= WITHDRAW: # <-- CHECK time.sleep(0.01) # <-- WINDOW: another thread re-reads the same balance balance -= WITHDRAW # <-- USE: the check is already stale # 8 threads pass the check before any of them spends -> balance goes negative What I understood about preventing it: # SAFE: make check + use ONE indivisible critical section with lock: if balance >= WITHDRAW: # check balance -= WITHDRAW # use -- nothing can run in between # no gap means no window: later threads either see the updated balance and are # refused, or they wait. Atomicity, not a bigger check. Sandbox check (local only, /tmp, threads only, no network): $ python3 toctou.py [vulnerable] start=100, each takes 30, 8 threads race [vulnerable] final balance = -140 (an overdraft that must be impossible) [fixed] final balance = 10 honoured 3/8 withdrawals, rest correctly refused What I understood: the vulnerable run ends at -140 . A balance that should never dip below zero is deeply negative, because all eight threads read the same stale "100" before any of them wrote. Nothing was hacked and no input was even malformed — the code was simply wrong the moment two callers overlapped. The fix is not a stronger check; a stronger check in the same place would fail the same way. The fix is to close the gap : hold a lock across check and use so no other thread can slip in. With the lock, three withdrawals go through and the other five are correctly refused — the invariant holds. The lesson that finally clicked: some bugs are not about what the code does, but about when it does it. Correctness under concurrency has to be designed, because under single calls this code looks perfectly fine. ---

Day 10 notes

Concept #10: random-forest bagging — deep tree test 0.581 (gap 0.329), 20-tree forest test 0.639 (gap 0.163). ✔ Security #10: TOCTOU race (CWE-367) — vulnerable balance -140, fixed balance 10. ✔ 1590 days left. One at a time.

Written by my own daily machine, checked by me.

← Back to the index

· Day 010 of 1600 · Matías Rathgeb


[ inicio ]   [ proyectos ]   [ posts ]   [ daylog ]


Página estática. Sin cookies, sin javascript, sin fuentes externas.
Contacto: ver inicio.