|
Última actualización: 2026-12-02
DAY 014 OF 1600 · 2026-10-01 Day 014 — The model that never trains, it just remembersA student's private learning log · one concept at a time. Date: 2026-10-01 · Day: 14 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #14 — k-Nearest Neighbours: no training step, just remember and voteFor the last ten days every model I wrote had a training phase. Gradient descent, decision trees, boosting, SVM — they all read the data once, do some heavy arithmetic, and then keep only a small bundle of numbers (weights, thresholds, support vectors). The data itself is thrown away. Today's model does the exact opposite, and that is the whole point of the family it belongs to: k-Nearest Neighbours (k-NN) is a lazy learner . k-NN does not learn anything. It stores every training point and does no arithmetic at all until you ask it for a prediction. When a new point arrives, it measures the distance from that point to every remembered point, sorts them, takes the k closest , and lets them vote: the majority label wins. That is the entire algorithm. The consequence is the interesting part, and it is a real trade-off, not a footnote. Training is instant (just keep the rows). Prediction is expensive (every single query scans the whole training set). A model like logistic regression flips that: it pays a lot up front so every later prediction is cheap. Which one is "better" depends entirely on **how often you predict versus how often you retrain** — a question about the deployment, not about the math. It also explains the two knobs. k decides how many neighbours vote: k=1 means "copy the nearest label", which is flexible but jumps around if one training point is noisy; a large k smooths the vote out but starts blurring the boundary between the classes. And distance has to mean something: I normalise features before using k-NN, because otherwise a column measured in thousands would drown out a column measured in fractions. What I tried today: I wrote k-NN from scratch with only the standard library — no numpy. I built two clouds of points that clearly belong to two classes, kept a separate test set the model never saw, and then measured accuracy for several values of k. The honest thing to watch is that k=1 scores a perfect 1.000 on the training data — it is memorising — but it is the test column that actually tells me whether the model is any good. #!/usr/bin/env python3 # knn_stdlib.py - k-nearest neighbours by hand, pure standard library. # MA01 (Machine Learning) - the "lazy learner": no training phase at all. # # Most models I studied so far (gradient descent, trees, SVM) had a TRAINING # step that does the hard work once and then throws the data away. k-NN does # the opposite: it remembers every training point and does the work at # prediction time -- look at the k closest remembered points and take a vote. import math, random def make_data(seed, n): rnd = random.Random(seed) rows = [] for _ in range(n): if rnd.random() < 0.5: rows.append((rnd.gauss(0.0, 1.0), rnd.gauss(0.0, 1.0), 0)) # class 0 else: rows.append((rnd.gauss(3.5, 1.0), rnd.gauss(3.5, 1.0), 1)) # class 1 return rows def dist(a, b): return math.hypot(a[0] - b[0], a[1] - b[1]) def knn_predict(train, point, k): # sort remembered points by distance, keep the k closest, majority vote ordered = sorted(train, key=lambda r: dist(r, point)) votes = {} for r in ordered[:k]: votes[r[2]] = votes.get(r[2], 0) + 1 # deterministic tie-break: highest count, then smallest label return max(votes.items(), key=lambda kv: (kv[1], -kv[0]))[0] def accuracy(train, test, k): right = sum(1 for r in test if knn_predict(train, r, k) == r[2]) return right / len(test) def test_knn(): # sanity: a point sitting on class-0 training data must come back 0 train = [(0.0, 0.0, 0), (10.0, 10.0, 1)] assert knn_predict(train, (0.1, 0.1), 1) == 0 assert knn_predict(train, (9.9, 9.9), 1) == 1 # k must not exceed the number of training points in a real run assert accuracy(train, train, 1) == 1.0 print("self-test: ok") if __name__ == "__main__": test_knn() train = make_data(seed=1, n=200) test = make_data(seed=99, n=100) # data the model never saw print("k train_acc test_acc") for k in (1, 3, 5, 15, 51): print(f"{k:<3} {accuracy(train, train, k):.3f} {accuracy(train, test, k):.3f}") Real output: self-test: ok k train_acc test_acc 1 1.000 0.980 3 0.995 0.990 5 1.000 0.990 15 1.000 0.980 51 1.000 0.980 What I understood from it: the training column is a lie I have to stop trusting. k=1 gets 1.000 on the data it memorised and only 0.980 on data it never saw — it is not learning a rule, it is repeating the answer key. The test column is what actually moved (0.980 → 0.990) when I let more neighbours vote. A model is judged on the data it did not see; everything else is recitation. --- Security #14 — Zip Slip: an archive entry whose name writes outside the folder (CWE-29)Path traversal (my Day 1) was about a request asking for a file outside the web root. Today's bug is the same idea wearing a different coat: the attacker never sends a path — they send an archive , and the harm happens when the server unpacks it. This is Zip Slip . The mechanism is almost insultingly simple. An archive is just a list of entries, and each entry carries a name . A malicious archive names one entry ../something.txt instead of something.txt . The extractor's code then joins that name onto the destination folder — something like os.path.join(dest, name) — and .. walks up and out of the folder the developer meant to write into. If the process runs as root, or the webroot is a few levels up, the file lands somewhere it can be served or executed. No traversal in the URL, no odd characters — just a normal-looking unzip that writes an attacker-chosen file to an attacker-chosen place. The pattern I studied: # VULNERABLE: the member name is trusted and joined straight onto dest target = os.path.join(dest, name) # name == "../pwned.txt" escapes dest with open(target, "wb") as f: f.write(z.read(name)) What I understood about preventing it: the fix is not to block the string .. — that is a blocklist and blocklists lose to a new encoding. The fix is to resolve the real path and prove it is still inside the destination before writing anything: # FIXED: resolve first, then refuse anything that lands outside dest real_dest = os.path.realpath(dest) + os.sep target = os.path.realpath(os.path.join(dest, name)) if not target.startswith(real_dest): continue # climbs out of the folder -> skip it Sandbox check (local only, everything under /tmp): [vulnerable extractor] wrote: /tmp/day14/zipslip/unpacked/innocent.txt wrote: /tmp/day14/zipslip/unpacked/../pwned.txt did a file land outside DEST? True -> I was written OUTSIDE the target folder [fixed extractor] wrote: /tmp/day14/zipslip/unpacked/innocent.txt BLOCKED: ../pwned.txt did a file land outside DEST? False What I understood: the dangerous part of this bug is where it lives — not in the code that receives user input, but in a utility the developer thinks is "just unpacking a file". The lesson I keep re-learning: any place where attacker-controlled text becomes a filesystem path is a place that needs a resolve-and-contain check, and the only reliable check is comparing the resolved real path against the intended root, not pattern-matching the bad strings. --- Day 14 notesConcept #14: k-NN code ran, output above (train vs test accuracy shown). ✔ Security #14: Zip Slip reproduced, then blocked, in a /tmp sandbox only. ✔ 1586 days left. One at a time. Written by my own daily machine, checked by me. · Day 014 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |