|
Última actualización: 2026-12-02
DAY 011 OF 1600 · 2026-09-26 Day 011 — Many weak learners, each fixing the last one's mistakesA student's private learning log · one concept at a time. Date: 2026-09-26 · Day: 11 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #11 — Boosting: grow weak learners one after another, not all at onceYesterday's forest (day 10) grew its trees side by side — each on its own bootstrap sample — and let them vote. The course calls that bagging . Today I learned the other half of the ensembles story, and it runs the opposite way: boosting . Instead of many independent trees, you grow them **one after another**, and each new one is told to focus on the rows the team still gets wrong. The slide deck (MA01, Week 8 — Advanced SVM and Ensembles ) puts the contrast in one line: *bagging generates complementary learners randomly, boosting generates them actively.* Random forests hope the trees' mistakes differ; boosting forces the next learner to look at exactly where the last one failed. The concrete version is AdaBoost . It keeps a weight on every training row, all equal at the start. Then, round after round: 1. Fit one weak learner — here a decision stump , a single feature/threshold split — that makes the smallest weighted error. 2. Score it: alpha = 0.5 · ln((1 − err) / err) . A stump barely better than guessing gets a small say; a good one gets a big say. 3. Raise the weight of every row it got wrong , lower the ones it got right, and renormalise. The next stump is now pulled toward the hard rows. 4. The final answer is the weighted vote of all the stumps: sign(Σ alpha·h) . The requirement the slides stress — *base learners should be simple, no overfitting* — is the whole trick. A stump is so weak it cannot memorise anything, so boosting has room to keep adding them without the ensemble eating itself. What I tried today: I built AdaBoost from scratch (pure standard library) on a circular decision boundary — label 1 inside a disk, 0 outside. A single axis-aligned stump cannot trace a curve, so it should be mediocre; a boosted team of stumps should carve the disk out. I ran it over 5 datasets with 5% label noise and averaged, so one lucky split could not fool me. #!/usr/bin/env python3 # adaboost_stumps.py - boost many weak stumps into one strong rule. # MA01 (Machine Learning), Week 8 "Advanced SVM and Ensembles". Pure stdlib. # # Boundary is a DISK around (0.5, 0.5): label = 1 inside, 0 outside. # The edge is curved, so no single axis-aligned stump can trace it -- one # stump is mediocre, but a boosted team of stumps carves the disk out. import math, random def make_disk(seed, n, noise): rnd = random.Random(seed) rows = [] for _ in range(n): x, y = rnd.random(), rnd.random() label = 1 if (x - 0.5) ** 2 + (y - 0.5) ** 2 < 0.09 else 0 if rnd.random() < noise: label = 1 - label rows.append((x, y, label)) return rows def stump(rows, weights): # Find the single (feature, threshold, direction) with lowest weighted error. 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 for pol in (1, -1): # which side -> class 1 err = 0.0 for r, w in zip(rows, weights): pred = 1 if (pol * (r[fi] - thr)) > 0 else 0 if pred != r[-1]: err += w if best is None or err < best[0]: best = (err, fi, thr, pol) return best def stump_predict(model, row): _, fi, thr, pol = model return 1 if (pol * (row[fi] - thr)) > 0 else 0 def adaboost(rows, rounds): n = len(rows) weights = [1.0 / n] * n team = [] for _ in range(rounds): err, fi, thr, pol = stump(rows, weights) err = min(max(err, 1e-10), 1 - 1e-10) alpha = 0.5 * math.log((1 - err) / err) team.append((alpha, (err, fi, thr, pol))) for i, r in enumerate(rows): pred = stump_predict((err, fi, thr, pol), r) weights[i] *= math.exp(-alpha if pred == r[-1] else alpha) s = sum(weights) weights = [w / s for w in weights] # renormalise return team def boost_predict(team, row): score = sum(a if stump_predict(m, row) == 1 else -a for a, m in team) return 1 if score > 0 else 0 NOISE, SEEDS, ROUNDS = 0.05, 5, 15 single_te, boost_te, single_tr, boost_tr = [], [], [], [] first_stumps = None for s in range(SEEDS): rows = make_disk(100 + s, 400, NOISE) rnd = random.Random(s) rnd.shuffle(rows) train, test = rows[:300], rows[300:] one = stump(train, [1.0 / len(train)] * len(train)) team = adaboost(train, ROUNDS) single_tr.append(sum(1 for r in train if stump_predict(one, r) == r[-1]) / len(train)) single_te.append(sum(1 for r in test if stump_predict(one, r) == r[-1]) / len(test)) boost_tr.append(sum(1 for r in train if boost_predict(team, r) == r[-1]) / len(train)) boost_te.append(sum(1 for r in test if boost_predict(team, r) == r[-1]) / len(test)) if s == 0: first_stumps = [(round(a, 3), m[1], round(m[2], 3), m[3]) for a, m in team[:3]] avg = lambda xs: sum(xs) / len(xs) print(f"{SEEDS} disk datasets, 300 train / 100 test, {NOISE:.0%} label noise, averaged:") print(f"Single best stump train {avg(single_tr):.3f} test {avg(single_te):.3f}") print(f"AdaBoost, {ROUNDS} stumps train {avg(boost_tr):.3f} test {avg(boost_te):.3f}") print(f"\nFirst 3 stumps of run 0 as (alpha, feature, threshold, direction):") for st in first_stumps: print(f" alpha={st[0]:>6} feature={st[1]} threshold={st[2]:>5} dir={st[3]:+d}") Real output ( python3 adaboost_stumps.py , Python 3.11.15): 5 disk datasets, 300 train / 100 test, 5% label noise, averaged: Single best stump train 0.699 test 0.684 AdaBoost, 15 stumps train 0.908 test 0.860 First 3 stumps of run 0 as (alpha, feature, threshold, direction): alpha= 0.416 feature=1 threshold=0.998 dir=+1 alpha= 0.306 feature=1 threshold=0.212 dir=+1 alpha= 0.228 feature=1 threshold=0.024 dir=-1 What I understood from it: the single stump tops out at 0.684 on rows it never saw — it can only cut the square on one axis, so the curved disk is simply beyond it. Fifteen boosted stumps reach 0.860 . That is the real difference from yesterday: the forest lowered its training score to win on test, but boosting raises both — 0.908 train, 0.860 test — because it is not averaging away noise, it is targeting the rows it keeps getting wrong. The three alphas in the output tell the story of the sequence: the first stump (0.416) is the strongest single cut, the next two are weaker (0.306, 0.228) and they flip directions (+1, +1, −1) — each one is patching the border of the disk the previous ones sliced off. That is "actively generating complementary learners": the later learners exist because the earlier ones were not enough. The thing I will keep: bagging fights variance (many noisy trees, average them), boosting fights bias (weak learners that cannot bend around the boundary), and the price of boosting is that the base learners must stay weak — if I fed it a deep tree, the ensemble would just overfit faster. --- Security #11 — Timing attack: a comparison that tells you how far you got (CWE-208)What I learned about this topic — contained, sandbox only, no live targets: Every injection I have studied so far corrupted the input . This one corrupts nothing and malforms nothing: the program is correct, and it still leaks its secret through how long it takes to say no . CWE-208 , observable timing discrepancy. The shape is one line of ordinary code: for a, b in zip(guess, secret): if a != b: return False # <-- returns EARLIER the sooner the bytes differ A comparison like == on strings, strcmp , or a naive MAC check **stops at the first wrong byte**. So the running time is proportional to the length of the correct prefix . Guess a token byte by byte: send a candidate, and the one whose first byte is right takes measurably longer than the ones that fail instantly. Keep the winning byte, move to the next position, repeat. After N × alphabet tries you have the whole secret — and you never had to guess it in one shot, which is exactly what makes an unguessable secret guessable. The subtle part is why this matters practically : the leak is tiny (a handful of nanoseconds per byte), so a single request tells you nothing. The attack is statistical — thousands of timings, averaged, pull the correct byte out of the noise. That is also why it hides: no crash, no error log, no weird input. Just a login endpoint that is a fraction of a millisecond slower when you guessed one more character right. I reproduced it in my own sandbox (/tmp): a comparator with the classic early-exit bug, over a made-up secret, no network and no real service. Because a bare Python byte loop only leaks ~45 ns per byte, I made each matched byte do a real, visible unit of work (a hash step) so the leak is measurable on this laptop. Then I ran the whole recovery, and afterwards the same test against a constant-time comparison. The pattern I studied: def leaky_compare(guess, secret): if len(guess) != len(secret): return False h = b"" for a, b in zip(guess, secret): if a != b: return False # bails out HERE, earlier or later h = hashlib.sha256(h + bytes([a])).digest() # work only while prefix is right return True # time to return == number of leading bytes you got right -> the leak What I understood about preventing it: import hmac # Compare in constant time: no early exit, always touch the same number of # bytes, regardless of where (or whether) they differ. hmac.compare_digest(candidate, secret) # returns bool, leaks nothing # Rule: NEVER compare secrets/passwords/tokens/MACs with == or strcmp. # Use a constant-time primitive. And do not branch on the secret's contents. Sandbox check (local only, /tmp, no network, no target): $ python3 timing_attack.py 1) Time leaks the length of the correct prefix. 0 correct bytes -> 832571 ns / 2000 runs 4 correct bytes -> 12150874 ns / 2000 runs 8 correct bytes -> 19583849 ns / 2000 runs 12 correct bytes -> 29540219 ns / 2000 runs 16 correct bytes -> 33622542 ns / 2000 runs 20 correct bytes -> 47888688 ns / 2000 runs 2) Recover the secret one byte at a time (slowest candidate wins). recovered: 'c' recovered: 'co' recovered: 'cor' recovered: 'corr' recovered: 'corre' recovered: 'correc' recovered: 'correct' recovered: 'correct-' recovered: 'correct-h' recovered: 'correct-ho' recovered: 'correct-hor' recovered: 'correct-hors' recovered: 'correct-horse' recovered: 'correct-horse-' recovered: 'correct-horse-b' recovered: 'correct-horse-ba' recovered: 'correct-horse-bat' recovered: 'correct-horse-batt' recovered: 'correct-horse-batte' recovered: 'correct-horse-batter' recovered: 'correct-horse-battery' Recovered : correct-horse-battery Actual : correct-horse-battery Match : True 3) Constant-time compare (hmac.compare_digest): flat, no leak. 21 bytes match -> 15680812 ns / 100k runs (mean of 5) 20 bytes match -> 13039077 ns / 100k runs (mean of 5) 0 bytes match -> 14760777 ns / 100k runs (mean of 5) What I understood: part 1 is the whole bug in one table — zero correct bytes returns in 0.8 ms per 2000 runs, twenty correct bytes take 47.9 ms . Nothing above leaks the value , but the shape of how long it took is a ruler laid against the secret. Part 2 is the payoff: the script walked the alphabet 21 times and printed the secret correct-horse-battery — recovered, `Match: True`, without ever submitting the full string. Part 3 is the fix in numbers: with hmac.compare_digest the time no longer depends on how many bytes match (15.7, 13.0, 14.8 ms — pure noise, no trend). The lesson I am keeping is that "correct" and "secure" are not the same question. This comparison never had a bug in the sense of returning a wrong answer — it always said yes or no correctly. It just answered too fast for the wrong cases , and that speed was the vulnerability. Security is not only what the code decides; sometimes it is how long it took to decide . --- Day 11 notesConcept #11: AdaBoost — single stump test 0.684, 15 boosted stumps test 0.860. ✔ Security #11: timing attack (CWE-208) — leak 0.8 ms → 47.9 ms by prefix length; secret recovered byte by byte; constant-time compare flat. ✔ 1589 days left. One at a time. Written by my own daily machine, checked by me. · Day 011 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |