|
Última actualización: 2026-12-02
DAY 007 OF 1600 · 2026-09-13 Day 007 — Finding groups with no labelsA student's private learning log · one concept at a time. Date: 2026-09-13 · Day: 7 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #7 — Clustering without labels: k-meansDays 5 and 6 were about supervised ideas: search that knows its goal, and a line that fits data I already labelled. Today is the opposite side of machine learning — unsupervised learning. I have points and **no labels at all**. Nobody tells me which point is which; I only have the coordinates. The question k-means asks is simple: *can I find a small number of "centres", so that every point sits close to the centre it is assigned to?* The algorithm is a loop of two steps the course keeps returning to: 1. Assign each point to the nearest centre (nearest by squared distance). 2. Update each centre to the mean of the points assigned to it. Then repeat until the centres stop moving. The number I want to watch is the inertia — the sum of squared distances from each point to its own centre. Every iteration can only lower it (or leave it), which is why the loop converges. The big practical lesson the course hammered: the starting centres matter . If I seed all three centres in the same corner, a whole real group can get swallowed. So people use k-means++ seeding, which spreads the seeds out, weighted by squared distance. What I tried today: 12 points that clearly form three groups (bottom left, top left, top right). I pretended not to know they were grouped, and clustered them with K=3 using k-means++ seeding and a fixed seed so the run is reproducible. #!/usr/bin/env python3 # kmeans.py — k-means clustering from scratch on 2D points. # MA01 (Machine Learning), unsupervised learning block. # Pure stdlib. Day 7 concept: clustering without labels. import math import random # 12 points, three obvious groups (we pretend we do not know them). POINTS = [ (1.0, 1.0), (1.5, 2.0), (2.0, 1.0), (1.2, 1.8), (8.0, 8.0), (8.5, 9.0), (9.0, 8.2), (8.2, 8.8), (1.0, 9.0), (1.6, 8.6), (2.2, 9.2), (1.4, 9.4), ] K = 3 def dist2(a, b): return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 def mean(pts): n = len(pts) return (sum(p[0] for p in pts) / n, sum(p[1] for p in pts) / n) def kmeanspp(points, k, rng): # k-means++ seeding: spread the first centroids out, weighted by # squared distance so far-away points are likely to be chosen. centroids = [points[rng.randrange(len(points))]] while len(centroids) < k: d2 = [min(dist2(p, c) for c in centroids) for p in points] total = sum(d2) r = rng.random() * total acc = 0.0 for p, w in zip(points, d2): acc += w if acc >= r: centroids.append(p) break return centroids def assign(points, centroids): return [min(range(len(centroids)), key=lambda i: dist2(p, centroids[i])) for p in points] def kmeans(points, k, iters=50): rng = random.Random(7) # fixed seed -> reproducible run centroids = kmeanspp(points, k, rng) for it in range(1, iters + 1): labels = assign(points, centroids) newc = [] for i in range(k): grp = [p for p, l in zip(points, labels) if l == i] newc.append(mean(grp) if grp else centroids[i]) shift = sum(math.dist(a, b) for a, b in zip(centroids, newc)) centroids = newc if shift < 1e-9: print(f"converged after {it} iterations") break return assign(points, centroids), centroids if __name__ == "__main__": labels, cents = kmeans(POINTS, K) for i, c in enumerate(cents): mags = [p for p, l in zip(POINTS, labels) if l == i] print(f"cluster {i}: centroid=({c[0]:.2f}, {c[1]:.2f}) n={len(mags)}") inertia = sum(dist2(p, cents[l]) for p, l in zip(POINTS, labels)) print(f"inertia (sum of squared distances): {inertia:.3f}") Real output ( python3 kmeans.py , Python 3.11.15): converged after 2 iterations cluster 0: centroid=(8.43, 8.50) n=4 cluster 1: centroid=(1.55, 9.05) n=4 cluster 2: centroid=(1.43, 1.45) n=4 inertia (sum of squared distances): 3.745 What I understood from it: the algorithm never saw a single label, yet it recovered the three groups perfectly — 4 points each , with centres sitting right inside each blob. It stopped after 2 iterations because the centres stopped moving. And I learned the seeding lesson the hard way: my first attempt seeded the three centres from the *first three points* (all in the bottom-left group), and the whole top-left group got merged into one giant cluster with an inertia of 98.17 . Switching to k-means++ seeding dropped the inertia to 3.75 — same algorithm, same data, different start . That is the real takeaway: k-means is only as good as where you start it, and "converged" does not automatically mean "correct". It means the loop stopped, not that it found the best answer. --- Security #7 — Insecure deserialization (pickle, CWE-502)What I learned about this topic — contained, sandbox only, no live targets: Serialization turns an object into bytes so it can be stored or sent; deserialization turns those bytes back into an object. The danger is that some formats do not just rebuild data — they can be told to run code while rebuilding. Python's pickle is exactly that format. A pickle stream can name a callable and its arguments inside a special method ( __reduce__ ), and pickle.loads() will call it at load time , before your code ever looks at the result. So if an app does pickle.loads(user_input) — a session cookie, a cache blob, an uploaded file, a message in a queue — then *whoever controls those bytes controls what runs on the server*. That is the whole bug of CWE-502. It is not a parsing crash; it is **remote code execution by design**. I built the payload in my own sandbox (/tmp) and pointed it at a marker file on my own disk — no network, no target, nothing real. The payload is deliberately boring: it just writes a one-line marker, which is enough to prove the code ran. The pattern I studied: class ExecOnLoad: def __reduce__(self): # pickle will CALL this callable while rebuilding the object return (os.system, ("echo ... > /tmp/day7/marker.txt",)) # VULNERABLE: attacker-controlled bytes go straight into pickle.loads pickle.loads(blob) # -> os.system(...) runs What I understood about preventing it: the rule is blunt — **never unpickle data you did not create and trust**. Prefer a data-only format (JSON) that physically cannot carry a callable. If you must use pickle, sign the bytes with a key only the server knows ( hmac ) and verify the signature before loading, so tampered input is rejected up front. At the process level: sandbox the worker, and never feed a cache/session/ queue payload straight into a loader. # SAFE: JSON carries data only — no callables, loading never runs code data = json.loads(raw) # {'user': 'student', 'role': 'reader'} # if pickle is unavoidable: check integrity first if not hmac.compare_digest(mac, hmac.new(key, blob, hashlib.sha256).digest()): raise ValueError("tampered payload") obj = pickle.loads(blob) # only after the MAC is verified Sandbox check (local only, /tmp, benign payload): $ python3 pickle_deser.py serialized size: 107 bytes marker file created after loads(): True marker content: 'code executed at unpickle time' json round-trip (data only, no code): {'user': 'student', 'role': 'reader'} What I understood: the marker file appeared before the script ever used the "object" — the write happened during pickle.loads() . 107 bytes of data were enough to run a command. That is the difference between a data format and an object format: JSON moved my dictionary around and ran nothing, while pickle executed my callable on the way in. The fix is not a clever parser setting — it is refusing to deserialize untrusted input at all, and treating any bytes that came from outside the server as hostile until proven otherwise. --- Day 7 notesConcept #7: k-means ran, 3 groups recovered, inertia 98.17 → 3.75 with k-means++ seeding. ✔ Security #7: insecure deserialization understood, sandbox only (/tmp), no live targets. ✔ 1593 days left. One at a time. Written by my own daily machine, checked by me. · Day 007 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |