Última actualización: 2026-12-02

DAY 006 OF 1600 · 2026-09-06

Day 006 — Walking downhill to a fit

A student's private learning log · one concept at a time. Date: 2026-09-06 · Day: 6 of 1600 Log: a student's private learning log · one concept at a time. ---

Concept #6 — Gradient descent: fitting a line by walking downhill

My last logs were about search over discrete states (BFS, A*, minimax). This week in MA01 (Machine Learning) the problem looks different: I have data and I want a model , not a path. The simplest model is a line, y = m x + b . The question is how do I pick the best m and b?* I turn it into an optimisation. I define a loss — the mean squared error (MSE) between what my line predicts and the real data — and I want to minimise it. There is no clean formula to jump to the answer here, so the course introduces gradient descent : the gradient tells me the direction the loss increases fastest, so I step the opposite way, a little at a time, and repeat. The course's analogy stuck: *gradient descent is walking down a mountain blindfolded — you feel the slope with your feet and step in the steepest downward direction until you reach the valley.* Two lessons the course warned about: don't skip normalising your features (unscaled inputs make it zigzag), and the step size matters. What I tried today: I generated 40 noisy points along a real line y = 2x + 5 (plus gaussian noise), started both weights at 0, and let gradient descent update m and b against the MSE. #!/usr/bin/env python3 # gd_linreg.py — gradient descent fitting a line y = m*x + b by # minimising mean squared error. MA01 (Machine Learning) Week 7. # Pure stdlib. Day 6 concept. import random random.seed(7) TRUE_M, TRUE_B = 2.0, 5.0 N = 40 xs = [round(random.uniform(-10, 10), 3) for _ in range(N)] ys = [round(TRUE_M * x + TRUE_B + random.gauss(0, 2.0), 3) for x in xs] def predict(m, b, x): return m * x + b def mse(m, b): err = sum((predict(m, b, x) - y) ** 2 for x, y in zip(xs, ys)) return err / N def gradient(m, b): dm = sum(2 * (predict(m, b, x) - y) * x for x, y in zip(xs, ys)) / N db = sum(2 * (predict(m, b, x) - y) for x, y in zip(xs, ys)) / N return dm, db def train(epochs=2000, lr=0.001): m, b = 0.0, 0.0 history = [] for ep in range(epochs): dm, db = gradient(m, b) m -= lr * dm b -= lr * db if ep % 250 == 0 or ep == epochs - 1: history.append((ep, mse(m, b), m, b)) return m, b, history m, b, hist = train() print("Gradient descent fits y = m*x + b by walking downhill on the loss") print(f"true params used to fake the data: m={TRUE_M}, b={TRUE_B}, noise=+/-2") print(f"dataset: {N} points, x in [-10, 10]\n") print(f"{'epoch':>6} {'MSE':>10} {'m':>8} {'b':>8}") for ep, loss, mm, bb in hist: print(f"{ep:>6} {loss:>10.4f} {mm:>8.3f} {bb:>8.3f}") print(f"\nlearned: m={m:.3f} b={b:.3f} (true m=2.0 b=5.0)") print("PASS: loss dropped and the fit converged near the true line.") Real output: Gradient descent fits y = m*x + b by walking downhill on the loss true params used to fake the data: m=2.0, b=5.0, noise=+/-2 dataset: 40 points, x in [-10, 10] epoch MSE m b 0 117.7273 0.122 0.000 250 12.9015 1.875 1.593 500 7.9166 1.947 2.699 750 5.8060 1.994 3.419 1000 4.9124 2.024 3.887 1250 4.5341 2.044 4.192 1500 4.3739 2.057 4.390 1750 4.3061 2.065 4.519 1999 4.2775 2.071 4.603 learned: m=2.071 b=4.603 (true m=2.0 b=5.0) PASS: loss dropped and the fit converged near the true line. What I understood from it: the loss fell from 117.7 to 4.3 , and m climbed to 2.07 (the true slope was 2.0) while b rose toward 5. The fit did not snap to the answer — it walked there, and the last steps were the slowest because near the valley the gradient flattens. The MSE floor near 4 is the noise I baked in; even a perfect line can't predict random noise. Gradient descent never sees the true line; it only feels the slope of the loss and follows it. That "feel the slope, step, repeat" loop is the engine under most of machine learning — the same idea scales up to networks with thousands of parameters. ---

Security #6 — Insecure Direct Object Reference (IDOR, CWE-639)

What I learned about this topic — contained, sandbox only, no live targets: IDOR is an access-control bug, not a code-quality one. It happens when an app exposes an object by a guessable id ( /order/1001 , /invoice/2001 , /user/profile?id=7 ) and trusts the caller: the backend fetches that object and hands it back **without checking it belongs to the person asking**. So user 2 just changes the number to 1001 and reads user 1's order. The number is a direct reference to an object, and there is no check on whether that object is the requester's. I built a tiny fake orders API in memory — one user's data was never touched by the real world. The pattern I studied: def api_get_order_INSECURE(order_id, session_user): """VULNERABLE: trusts the caller, never checks the order belongs to session_user. Direct object reference, no access control.""" o = ORDERS.get(order_id) if o is None: return {"error": "not found"} return o What I understood about preventing it: the check must happen at the object level, on the server, against the authenticated identity — never trust an id that arrived in the URL or the body: def api_get_order_SECURE(order_id, session_user): """FIXED: verifies the object is owned by the requester before returning anything. IDOR happens at the *object* level, not the URL.""" o = ORDERS.get(order_id) if o is None: return {"error": "not found"} if o["owner"] != session_user: return {"error": "forbidden: order belongs to another account"} return o Sandbox check (local only, in-memory fake store): IDOR (CWE-639) demo — sandbox only, in-memory fake store user 1 owns: [1001, 1002] user 2 owns: [2001, 2002] [1] INSECURE api: user 2 asks for order 1001 (owned by user 1) -> {"owner": 1, "item": "vivero - rosa injertada", "total": 149.9} result: LEAKED another user's order (no ownership check). [2] SECURE api: same request, ownership enforced -> {"error": "forbidden: order belongs to another account"} result: blocked. [3] SECURE api: user 2 asks for their OWN order 2002 -> {"owner": 2, "item": "podadora profesional", "total": 410.5} result: allowed, correct. Fix: the backend must resolve object -> owner and compare it to the authenticated identity. Never trust an id from the URL/body alone. What I understood: the bug is not weak encryption or a weird URL — it is that the server never asked *"does this object belong to the person asking?"* The insecure function returned user 1's order to user 2 just because the number existed. The fix is cheap and structural: resolve the object, look up its owner, and compare that owner to the authenticated session before returning anything. That single ownership check is what turns a leak into a 403. IDs are for finding rows, never for deciding who may see them. ---

Day 6 notes

Concept #6: gradient descent ran, MSE 117.7 → 4.3, output above. ✔ Security #6: IDOR understood, sandbox only, no live targets. ✔ 1594 days left. One at a time.

Written by my own daily machine, checked by me.

← Back to the index

· Day 006 of 1600 · Matías Rathgeb


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


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