|
Última actualización: 2026-12-02
DAY 016 OF 1600 · 2026-10-09 Day 016 — The score that changed every time I reshuffled the rowsA student's private learning log · one concept at a time. Date: 2026-10-09 · Day: 16 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #16 — k-fold cross-validation: one split is a coin flip, k folds are a measurementYesterday the lesson was that a single accuracy number can lie. Today is the companion problem: even when the metric is right, the way I split the data can make the number move. I had been testing every model with one holdout — cut off 30% of the rows, score on them, done. The cut is random, so a different shuffle gives a different score, and I never knew how much of the score was the model and how much was the luck of the split. The MA01 material (mock test, Metrics, performance and validation , Q1) asks exactly this: when you only have a limited amount of data , what validation method do you recommend? The answer it gives is **cross-validation with many folds** — with little data, the extra compute is not a problem, and cross-validation gives the most detailed validation information. The idea is simple once it clicks. Instead of spending a chunk of the data on testing and throwing it away, cut the data into k equal folds . Train on k−1 of them, test on the one fold left out, and repeat so that **every fold is the test set exactly once**. Then average the k scores. No row is wasted, and no single lucky shuffle decides the verdict. The spread of the fold scores also tells me something a single number never did: how stable the estimate is. When data is truly tiny, k can be the number of rows itself (leave-one-out). What I tried today: rather than trust the idea, I measured it. I built the same overlapping two-class dataset and the same 1-nearest-neighbour classifier, then compared two estimators over ten different shuffles: a single 70/30 holdout versus 5-fold cross-validation. Standard library only, no ML libraries. #!/usr/bin/env python3 # cross_validation.py - one split is a coin flip; k-fold is a measurement. # MA01 (Machine Learning) - Week: metrics, performance and validation. # Mock-test Q1: "What validation method would you recommend when only a # limited amount of data is available?" -> cross-validation with many folds. import random import math def make_data(seed, n=200): # two overlapping classes on one feature; a classifier CAN separate them # but not perfectly, so the accuracy estimate has real uncertainty. rnd = random.Random(seed) rows = [] for _ in range(n): y = 1 if rnd.random() < 0.5 else 0 x = rnd.gauss(1.0 if y == 1 else 0.0, 1.0) rows.append((x, y)) return rows def knn1_predict(train, x): # 1-nearest neighbour on a single feature best = min(train, key=lambda r: abs(r[0] - x)) return best[1] def accuracy(train, test): if not test: return 0.0 return sum(1 for x, y in test if knn1_predict(train, x) == y) / len(test) def holdout_estimate(rows, frac, seed): # split once, test on the held-out part, throw that part away forever rnd = random.Random(seed) idx = list(range(len(rows))) rnd.shuffle(idx) k = int(len(rows) * frac) test = [rows[i] for i in idx[:k]] train = [rows[i] for i in idx[k:]] return accuracy(train, test) def kfold_scores(rows, k, seed): rnd = random.Random(seed) idx = list(range(len(rows))) rnd.shuffle(idx) folds = [idx[i::k] for i in range(k)] # deal rows round-robin into k folds scores = [] for i in range(k): test = [rows[j] for j in folds[i]] train = [rows[j] for f in range(k) if f != i for j in folds[f]] scores.append(accuracy(train, test)) return scores def cv_estimate(rows, k, seed): s = kfold_scores(rows, k, seed) return sum(s) / len(s) def mean_std(vals): m = sum(vals) / len(vals) sd = math.sqrt(sum((v - m) ** 2 for v in vals) / len(vals)) return m, sd def test_cv(): # deterministic tiny case: perfectly separable, 1-NN must score 1.0 train = [(0.0, 0), (1.0, 1)] assert knn1_predict(train, 0.1) == 0 assert knn1_predict(train, 0.9) == 1 assert accuracy(train, [(0.2, 0), (0.8, 1)]) == 1.0 print("self-test: ok") Real output: self-test: ok data: 200 rows, two overlapping classes (so accuracy has real noise) single 70/30 holdout, ten different shuffles: shuffle seed=0 holdout acc=0.683 shuffle seed=1 holdout acc=0.683 shuffle seed=2 holdout acc=0.600 shuffle seed=3 holdout acc=0.600 shuffle seed=4 holdout acc=0.667 shuffle seed=5 holdout acc=0.733 shuffle seed=6 holdout acc=0.783 shuffle seed=7 holdout acc=0.650 shuffle seed=8 holdout acc=0.650 shuffle seed=9 holdout acc=0.667 -> estimate jumps around: mean=0.672 std=0.053 min=0.600 max=0.783 5-fold cross-validation, ten different shuffles (mean of folds): shuffle seed=0 cv acc=0.685 shuffle seed=1 cv acc=0.660 shuffle seed=2 cv acc=0.655 shuffle seed=3 cv acc=0.670 shuffle seed=4 cv acc=0.670 shuffle seed=5 cv acc=0.690 shuffle seed=6 cv acc=0.675 shuffle seed=7 cv acc=0.625 shuffle seed=8 cv acc=0.650 shuffle seed=9 cv acc=0.665 -> estimate holds still: mean=0.665 std=0.018 min=0.625 max=0.690 one 5-fold run, fold by fold (seed=1): fold 0: acc=0.600 fold 1: acc=0.650 fold 2: acc=0.725 fold 3: acc=0.625 fold 4: acc=0.700 What I understood from it: the same model, the same data, and the holdout number still swam between 0.600 and 0.783 just from reshuffling — a spread of nearly 0.18 with a standard deviation of 0.053. Cross-validation over the same ten shuffles stayed between 0.625 and 0.690 , a standard deviation of 0.018 , roughly a third as wide. The mean was almost the same (0.672 vs 0.665), which is the point: cross-validation did not make the model better, it made the estimate cheaper to trust. A single split can report a number that is mostly luck. And the per-fold scores (0.600 … 0.725) are useful too — that scatter is the honest uncertainty of a 200-row dataset, which one number hides. The course was right about the trade-off: folds cost more compute to buy a steadier measurement, and when data is scarce, steadiness is worth more than time. --- Security #16 — NoSQL operator injection: a login that trusts the type of the input (CWE-943)Every earlier bug today smuggled something inside a value — a path segment, a query string, a template, a field the form never showed. This one does not put anything inside a value. It changes the type of the value, and the query layer obeys it. The setting is a login that looks up a user by a filter document, the way document databases take queries: {"username": "alice", "password": "hunter2"} . Ordinarily each field maps to a string and means "equals this". But that filter usually arrives as JSON , and JSON lets a field hold an object instead of a string. So the attacker sends: {"username": "admin", "password": {"$ne": null}} Read as an operator, {"$ne": null} does not mean "the password is the text $ne: null ". It means "the password is not null" — and every account with a password satisfies that. The attacker never learns or guesses the admin password; they replace the equality test with a condition they control. {"$gt": ""} works the same way ("password is greater than the empty string"). SQL injection needs a string, a quote and a comment; this needs nothing but shipping a dict where a string was expected. The pattern I studied: # VULNERABLE: the query layer evaluates a dict value as an operator. # {"password": {"$ne": null}} becomes "password != null" -> matches every user. users = db.find(request_body) # attacker controls the types in request_body What I understood about preventing it: the fix is not to strip a list of known operators — that is a blocklist and the next operator name defeats it. The fix is to state what each field is allowed to be, and reject anything that is not that type . A password is a string; if the value is not a string, it never reaches the query. # FIXED: pin the allowed fields and require the exact type each one expects. if field not in ALLOWED: return False if not isinstance(value, str): return False # a dict/operator can never pass Sandbox check (local only, in-memory list, no network, no real database, no real credentials): self-test: ok honest login alice / hunter2 vulnerable: ['alice'] fixed: ['alice'] honest login admin / wrong vulnerable: [] fixed: [] attack login admin / {"$ne": null} vulnerable: ['admin'] <- bypass, password never guessed fixed: [] attack login admin / {"$gt": ""} vulnerable: ['admin'] <- bypass again fixed: [] What I understood: the honest logins behave identically in both versions — that is the whole trap. The code "works" on every test a developer writes, because a developer tests with strings. The difference only appears when the attacker changes the type of a field, and the vulnerable version logs in as admin without ever knowing the password. It is the same shape as the injection bugs I studied before, moved up a layer: the danger is not a bad character inside the input, it is the structure of the input being taken as instructions. Any query built from a request body has to fix the type of each field before it is trusted — the client chooses the shape, so the shape cannot be the query. --- Day 16 notesConcept #16: cross-validation code ran, output above (holdout spread 0.600–0.783 vs k-fold 0.625–0.690). ✔ Security #16: NoSQL operator injection reproduced, then blocked, in a /tmp sandbox only. ✔ 1584 days left. One at a time. Written by my own daily machine, checked by me. · Day 016 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |