Última actualización: 2026-12-02

DAY 012 OF 1600 · 2026-09-27

Day 012 — The line with the widest street between the classes

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

Concept #12 — Support Vector Machines: many lines split two classes, only one leaves the widest street

For the last few days I separated classes with trees and forests, which cut the space with axis-aligned questions. Today I went back to a straight line — the simplest separator there is — and found that even a line has a "good" and a "bad" version, and the good one is the whole point of the support vector machine . Two clouds of points, one class on each side. A perceptron stops the moment it finds any line that gets the training points right. It does not care if the line passes a hair away from a point — it is satisfied. The course slides (MA01, Week 8 — Advanced SVM and Ensembles ) call the extra thing the SVM adds the margin : the width of the empty street running between the two classes, with the line down the middle of it. The SVM's rule is: maximise that street . The points sitting on the edges of the street are the support vectors — they are the only ones that decide where the line goes. Move any other point and the line does not budge. What I tried today: I built both from scratch, pure standard library, on five separate two-cloud datasets. The perceptron updates weights only on mistakes. The SVM uses the hinge loss : a point that is already outside the street costs nothing, a point inside the street (or on the wrong side) is pushed out, and a small L2 regulariser keeps the weights as small as they can be while still fitting — small weights mean a wide street. Then I measured both the accuracy on unseen points and the width of the street each one left. #!/usr/bin/env python3 # svm_hinge.py - a linear support vector machine by subgradient descent. # MA01 (Machine Learning), Week 8 "Advanced SVM and Ensembles". Pure stdlib. # # Two clouds of points, separated by a hidden line. A perceptron just needs # ANY line that gets them right; an SVM wants the line with the WIDEST street # (margin) between the classes. That extra objective is what the hinge loss # adds: points already outside the street cost 0, points inside the street -- # or on the wrong side -- are pushed out. We measure the margin and compare # both classifiers on fresh test points. import random, math def make_data(seed, n): rnd = random.Random(seed) rows = [] for _ in range(n): if rnd.random() < 0.5: x, y, lab = rnd.gauss(-1.2, 0.55), rnd.gauss(-0.9, 0.55), -1 else: x, y, lab = rnd.gauss(1.2, 0.55), rnd.gauss(0.9, 0.55), +1 rows.append((x, y, lab)) return rows def perceptron(rows, epochs=50): w1 = w2 = b = 0.0 for _ in range(epochs): for x, y, lab in rows: if lab * (w1 * x + w2 * y + b) <= 0: w1 += lab * x; w2 += lab * y; b += lab return w1, w2, b def svm_hinge(rows, epochs=300, lr=0.01, C=1.0): w1 = w2 = b = 0.0 n = len(rows) for _ in range(epochs): g1 = g2 = gb = 0.0 for x, y, lab in rows: margin = lab * (w1 * x + w2 * y + b) if margin < 1: # inside the street -> have to push g1 += -lab * x; g2 += -lab * y; gb += -lab else: # already outside -> only regularise g1 += 0.0; g2 += 0.0 # L2 regularisation w -> wants the SMALLEST weights that still fit g1 += w1 / C; g2 += w2 / C w1 -= lr * g1 / n; w2 -= lr * g2 / n; b -= lr * gb / n return w1, w2, b def margin_of(w1, w2, b): norm = math.hypot(w1, w2) return 2.0 / norm if norm else 0.0 def acc(model, rows): w1, w2, b = model return sum(1 for x, y, lab in rows if (1 if w1 * x + w2 * y + b > 0 else -1) == lab) / len(rows) SEEDS = 5 p_tr = p_te = s_tr = s_te = 0.0 p_marg = s_marg = 0.0 for s in range(SEEDS): rows = make_data(100 + s, 400) random.Random(s).shuffle(rows) train, test = rows[:300], rows[300:] p = perceptron(train) sv = svm_hinge(train) p_tr += acc(p, train); p_te += acc(p, test) s_tr += acc(sv, train); s_te += acc(sv, test) p_marg += margin_of(p[0], p[1], p[2]) s_marg += margin_of(sv[0], sv[1], sv[2]) print(f"{SEEDS} two-cloud datasets, 300 train / 100 test, averaged:") print(f"Perceptron train {p_tr/SEEDS:.3f} test {p_te/SEEDS:.3f} margin {p_marg/SEEDS:.3f}") print(f"Linear SVM train {s_tr/SEEDS:.3f} test {s_te/SEEDS:.3f} margin {s_marg/SEEDS:.3f}") Real output ( python3 svm_hinge.py , Python 3.11.15): 5 two-cloud datasets, 300 train / 100 test, averaged: Perceptron train 1.000 test 0.992 margin 0.599 Linear SVM train 0.997 test 0.994 margin 1.805 What I understood from it: the perceptron is perfect on the rows it saw — 1.000 — and still scores lower on rows it never saw ( 0.992 vs 0.994 ), which is exactly the overfitting lesson from day 8 in a different costume. The SVM gives up a little on training (0.997, it deliberately tolerates a point or two inside the street) and buys the better test score. But the number that matters is the last column: the perceptron's street is 0.599 wide, the SVM's is 1.805 — triple the width. A wide street is not cosmetic; it is a buffer. The perceptron's line merely missed the training points, so any new point near the boundary can flip it. The SVM's line is as far as it can be from both classes, so new points have to travel much further before they land on the wrong side. That is the whole trade: a classifier that fits perfectly versus a classifier that leaves itself room — and the room is what survives contact with data it has not seen. The support vectors are the price of the room, and there are only ever a few of them. ---

Security #12 — ReDoS: a regex that answers correctly, just not quickly (CWE-1333)

What I learned about this topic — contained, sandbox only, no live targets: Day 11 was a comparison that leaked how long it took to say no. This is almost the same shape from the other side: a regular expression that answers correctly — it matches what it should and rejects what it should — and still takes down the server, because of how long it takes to say no. CWE-1333 , inefficient regular expression complexity. Most regex engines (Python's re , PCRE, JavaScript, Java) are backtracking engines. To match ^(a+)+$ they try one way to split the input, fail, undo a step, try another. On a string that almost matches, the number of ways to try explodes: the inner + and the outer + both want to decide how many of the a 's to take, so the engine enumerates essentially every partition of the run of a 's — and that doubles with each extra character. This is the famous nested quantifier ReDoS. It is not a bug you can spot as "wrong output"; the regex is semantically correct. The bug is complexity . The danger is that the pattern often comes from outside — a user-supplied search, a validation rule, a routing URL — and it runs against a long piece of attacker-chosen input. One request with a short crafted string pins a CPU core; a few of them, and the worker pool is gone. It needs no bug in the application's logic at all. I reproduced it in my sandbox (/tmp): the vulnerable nested-quantifier pattern against the same input handled by a linear-time rewrite, on input lengths from 18 to 28 characters. Nothing leaves the machine; the string is made up. The pattern I studied: import re VULN = re.compile(r"^(a+)+$") # nested quantifier: exponential backtracking VULN.match("a" * 28 + "!") # correct answer ("no match") after ~11 seconds What I understood about preventing it: import re, re2 # (or the regex module, or a timeout-wrapped call) SAFE = re.compile(r"^a+$") # quantify the run ONCE -> linear time # Rules: # - Never let a quantifier sit inside another quantifier ((a+)+, (a|a)*, .*.*). # - Make alternatives disjoint and anchor the pattern. # - Never compile a regex from untrusted input; if you must, prefer a # non-backtracking engine (RE2/Go, Rust regex) or cap the input length. # - Any regex run on user input should have a time budget, not just a match rule. Sandbox check (local only, /tmp, no network, no target): $ python3 redos.py Input = 'a'*n + '!' (does NOT match either pattern) n vulnerable (a+)+ safe a+ 18 11.81 ms 1.0 us 20 47.51 ms 1.4 us 22 189.95 ms 2.0 us 24 740.37 ms 1.9 us 26 2620.23 ms 1.3 us 28 10938.90 ms 15.4 us The engine is not wrong -- it always answers 'no match'. It is the time it takes to say no that grows without bound. What I understood: the vulnerable column multiplies by roughly **4× every two characters — 11.8 ms → 47.5 → 190 → 740 → 2620 → 10.9 seconds**. Every extra two a 's is four times the work, because each a doubles the number of ways the engine can split the run between the inner and outer quantifier. The safe rewrite handles the same string, including the longest one, in **15 microseconds** — and I could keep adding a 's all day without it noticing. Both patterns are correct; both return "no match" on every line. The difference is entirely in the cost of returning it. That is the same lesson as day 11 in new clothing: "does it give the right answer?" is not the security question. "Can an attacker make the right answer expensive?" is. A pattern is code, and code with a hidden exponential is a denial-of-service waiting for one short input. ---

Day 12 notes

Concept #12: linear SVM — perceptron margin 0.599 vs SVM margin 1.805; SVM test 0.994 vs perceptron 0.992. ✔ Security #12: ReDoS (CWE-1333) — ^(a+)+$ 11.8 ms → 10.9 s as input grows; ^a+$ flat at microseconds. ✔ 1588 days left. One at a time.

Written by my own daily machine, checked by me.

← Back to the index

· Day 012 of 1600 · Matías Rathgeb


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


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