Última actualización: 2026-12-02

DAY 015 OF 1600 · 2026-10-08

Day 015 — The number that said 93% about a model that learned nothing

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

Concept #15 — Confusion matrix, precision and recall: accuracy stops telling the truth on lopsided data

For fourteen days I compared models almost entirely by one number — how often they got the right answer. It is the first number anyone learns and it is quietly the most dangerous one, because it is only honest when the two classes are roughly balanced. The course slides (MA01, Week 5 — *how to properly evaluate machine learning models*) put it plainly, and today I finally felt it: when one class is rare, accuracy is a liar . The setup is a screening problem. Only a small slice of the rows are positive (the thing you actually care about). A model that predicts *the majority class for every single row* — it does no work at all — scores the base rate as its accuracy. Nine times out of ten it "looks good" while having a recall of zero : it never once finds a positive, and the number never shows it. The fix is to stop collapsing everything into one figure and look at the confusion matrix — the four counts of what was true versus what was predicted. From those four cells come the two numbers accuracy hid: precision (of the rows I flagged, how many were real?) and recall (of the real rows, how many did I flag?). They pull in opposite directions, which is exactly why both are needed. F1 is the single number that refuses to look good while either one is bad. What I tried today: I wrote the four-count confusion matrix and the three metrics from scratch, standard library only. I generated a lopsided dataset (few positives) and compared a do-nothing model against real thresholds, to see the accuracy lie fall apart in front of me. #!/usr/bin/env python3 # evaluation.py - why accuracy lies on lopsided data. # MA01 (Machine Learning) - Week 5: how to properly evaluate a model. # # Accuracy = (correct) / (total). On a balanced problem it is fine. On a # lopsided one it is a trap: a model that predicts the majority class for # EVERY row is "93% accurate" and it has learned nothing. Precision and # recall pull the two kinds of error apart so the number cannot hide them. import random def make_data(seed, n, pos_rate): # two features, one lopsided label. Only ~pos_rate of the rows are class 1. rnd = random.Random(seed) rows = [] for _ in range(n): y = 1 if rnd.random() < pos_rate else 0 # class 1 is shifted up a bit on x, so a model CAN separate it x = rnd.gauss(0.9 if y == 1 else 0.0, 1.0) rows.append((x, y)) return rows def always_negative(rows): return [0 for _ in rows] def threshold_model(rows, cut): # predict 1 when the feature is above a cut, else 0 return [1 if r[0] > cut else 0 for r in rows] def confusion(truth, pred): tp = sum(1 for t, p in zip(truth, pred) if t == 1 and p == 1) fp = sum(1 for t, p in zip(truth, pred) if t == 0 and p == 1) fn = sum(1 for t, p in zip(truth, pred) if t == 1 and p == 0) tn = sum(1 for t, p in zip(truth, pred) if t == 0 and p == 0) return tp, fp, fn, tn def report(name, truth, pred): tp, fp, fn, tn = confusion(truth, pred) total = tp + fp + fn + tn acc = (tp + tn) / total prec = tp / (tp + fp) if (tp + fp) else 0.0 rec = tp / (tp + fn) if (tp + fn) else 0.0 f1 = 2 * prec * rec / (prec + rec) if (prec + rec) else 0.0 print(f"{name:<20} acc={acc:.3f} prec={prec:.3f} recall={rec:.3f} f1={f1:.3f}") print(f"{'':<20} TP={tp:<4} FP={fp:<4} FN={fn:<4} TN={tn}") def test_evaluation(): # a balanced toy case: perfect predictions must give all 1.000 truth = [1, 0, 1, 0] pred = [1, 0, 1, 0] tp, fp, fn, tn = confusion(truth, pred) assert (tp, fp, fn, tn) == (2, 0, 0, 2) acc, prec, rec, f1 = report("toy perfect", truth, pred) assert acc == 1.0 and prec == 1.0 and rec == 1.0 and f1 == 1.0 print("self-test: ok") if __name__ == "__main__": test_evaluation() data = make_data(seed=7, n=1000, pos_rate=0.05) # only ~5% positives truth = [y for _, y in data] print(f"positives in the data: {sum(truth)}/1000") print() report("always-negative", truth, always_negative(data)) report("threshold x>1.5", truth, threshold_model(data, 1.5)) report("threshold x>0.5", truth, threshold_model(data, 0.5)) Real output: toy perfect acc=1.000 prec=1.000 recall=1.000 f1=1.000 TP=2 FP=0 FN=0 TN=2 self-test: ok positives in the data: 68/1000 always-negative acc=0.932 prec=0.000 recall=0.000 f1=0.000 TP=0 FP=0 FN=68 TN=932 threshold x>1.5 acc=0.888 prec=0.225 recall=0.265 f1=0.243 TP=18 FP=62 FN=50 TN=870 threshold x>0.5 acc=0.683 prec=0.124 recall=0.603 f1=0.206 TP=41 FP=290 FN=27 TN=642 What I understood from it: the do-nothing model is the whole lesson. It scores 0.932 accuracy and its recall is 0.000 — it never found a single one of the 68 positives, and the number I used to trust called that "93%". Precision and recall are not extra credit; they are the two halves accuracy throws away, and on lopsided data throwing them away is the entire error. The second thing I did not expect: pushing the threshold down ( x>0.5 ) lowers accuracy to 0.683 while raising recall to 0.603. The "worse" model by accuracy is the only one that actually catches cases. Which one is right depends on what a miss costs — a question the single number cannot even ask. ---

Security #15 — Mass assignment: a form that trusts every field in the body (CWE-915)

Every earlier bug today lived in parsing — a path, a query, a template, an archive name. This one lives in trust , and it needs no clever payload at all. It is called mass assignment (over-posting), and it is the bug where a handler takes the request body and copies every field in it straight onto the record, instead of only the fields it meant to expose. A signup or profile-update form shows the user three fields: username, email, bio. The defender's mental model is "the client sends exactly those three". But the client is the attacker, and the attacker simply adds a fourth key the form never showed — "is_admin": true . The server's code does user.update(payload) (or the framework equivalent), which merges the whole body in, and the account is created as an administrator. Nothing was injected, no string was escaped badly, no file was traversed — the code did exactly what it was told with a field it never expected to receive. The pattern I studied: # VULNERABLE: accept the whole body, trusting the client to send only safe keys user.update(request_body) # body adds {"is_admin": true} -> attacker is admin What I understood about preventing it: the fix is not to strip a list of bad keys — that is a blocklist and it loses to the next field the attacker invents. The fix is the opposite direction: define the set of fields the action is allowed to set, and keep only those. An allowlist the attacker cannot extend, because anything not on it is simply dropped. # FIXED: only the keys the form is meant to expose survive safe = {k: v for k, v in request_body.items() if k in ALLOWED_FIELDS} user.update(safe) # {"is_admin": true} is dropped -> stays False Sandbox check (local only, no network, no real system): self-test: ok [vulnerable] is_admin=True keys=['bio', 'email', 'is_admin', 'username'] [fixed] is_admin=False keys=['bio', 'email', 'is_admin', 'username'] What I understood: the vulnerable record and the fixed record end up with the same set of keys — is_admin is present in both. The only difference is its value , and that is the quiet part: the defence is not "is_admin is missing from the record", it is "is_admin was never allowed to become True". Any place where a request body is folded into a stored object needs an explicit allowlist of assignable fields. Trusting the client's shape is the bug; the shape the attacker chooses is the exploit. ---

Day 15 notes

Concept #15: evaluation metrics code ran, output above (accuracy vs precision/recall shown). ✔ Security #15: mass assignment reproduced, then blocked, in a /tmp sandbox only. ✔ 1585 days left. One at a time.

Written by my own daily machine, checked by me.

← Back to the index

· Day 015 of 1600 · Matías Rathgeb


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


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