AI from scratch · Model zoo 8 of 10 · Support vector machines
Support vector machines
Before deep learning, support vector machines were the most respected classifiers there were: elegant math, one global optimum, and state-of-the-art results on handwriting and text. They're less common now, but their two ideas live on everywhere: the margin (don't just separate the classes, separate them with room to spare) and the kernel trick (bend the boundary by measuring similarity, without ever building new columns).
1. The idea in one picture: the widest street
Many lines separate two clouds. An SVM picks the one in the middle of the widest street between them: the dashed lines are the street's edges, the solid one its middle. The circled dots are the support vectors: the dots on or inside the edges. Only they decide where the street goes; move any other dot (not across the street) and nothing changes.
Pick the bendy kernel and slide γ to the top. Predict first: what happens to the support vectors and to validation accuracy?
- Almost every dot becomes a support vector, training accuracy nears 100%, validation drops
- The boundary gets smoother
- Nothing changes, it just trains slower
An SVM finds the boundary with the widest margin, decided only by the points nearest to it; a kernel lets that boundary bend by measuring similarity instead of adding columns.
2. How it learns: hinge loss plus a price on narrow streets
With labels \(y_i = \pm 1\) and a score \(f(x) = w \cdot x + b\), the street's edges are where \(f = \pm 1\), so its width is \(2/\lVert w \rVert\): small weights mean a wide street. The SVM minimizes
\[ \tfrac12 \lVert w \rVert^2 \;+\; C \sum_i \max\big(0,\; 1 - y_i f(x_i)\big) \]
The second part is the hinge loss: zero for a dot safely on its side beyond the edge, growing linearly as it slips into the street or across. Compare page 2's log-loss, which never quite reaches zero: every dot pulls a little, however far away. With hinge loss, far dots pull not at all, which is exactly why only the support vectors matter. C trades the two: a small C accepts dots inside the street for a wider one (smoother, more support vectors); a large C narrows the street to put every dot on its side.
A dot sits on the correct side with \(y f(x) = 3\), far beyond the edge. How much does it change the fitted SVM if you delete it?
- A little: every point counts
- Not at all: its hinge loss is zero and it's not a support vector
- A lot: it's the most confident point
Why the dual form enables the kernel trick
- Write the loss above as a problem with rules: give each point a slack \(\xi_i \ge 0\) (its hinge loss), then minimize \(\tfrac12 \lVert w \rVert^2 + C \sum_i \xi_i\) subject to \(y_i(w \cdot x_i + b) \ge 1 - \xi_i\).
- Each rule gets a Lagrange multiplier \(\alpha_i\) (C5's \(\mu\), one per point): how hard that point pushes on the street. Setting the slope with respect to \(w\) to zero gives \(w = \sum_i \alpha_i y_i x_i\). Points safely outside the street don't push, so their \(\alpha_i = 0\): only support vectors count, and none by more than \(C\).
- Put that \(w\) back in, and the problem is about the \(\alpha\)'s alone (the dual):
\[ \max_\alpha \sum_i \alpha_i \;-\; \tfrac12 \sum_i \sum_j \alpha_i \alpha_j y_i y_j \,(x_i \cdot x_j) \quad \text{with } 0 \le \alpha_i \le C,\; \sum_i \alpha_i y_i = 0 \]
- The points appear only in dot products \(x_i \cdot x_j\), and so does the score of a new point: \(f(x) = \sum_i \alpha_i y_i \,(x_i \cdot x) + b\).
- So swap every dot product for a kernel \(K(a, b) = \phi(a) \cdot \phi(b)\), a dot product of new columns computed without building them. For 2 columns, \((a \cdot b + 1)^2\) equals \(\phi(a)\cdot\phi(b)\) where \(\phi\) lists 6 columns (1, each column, each square, the product), each with the right constant in front.
- The RBF kernel \(K(a, b) = e^{-\gamma \lVert a - b \rVert^2}\) is a dot product in infinitely many columns, computed from a distance. The SVM fits a straight street in a space too big to build, and on the map it bends. The cost: training compares every pair of points (section 4).
3. Build it: a linear SVM by subgradient descent, in NumPy
Hinge loss has a corner at 1, so instead of a gradient there's a subgradient: for a dot inside the street, \(-y_i x_i\); for a safe one, 0. Plain descent on that, with the \(\lVert w \rVert^2\) term as a shrink:
4. Where it shines, where it breaks
Shines: medium-sized data with many columns. On digits, the RBF SVM gets 98.7% with default settings and 99.1% tuned, the best of any model in the zoo. On the 7,166 word columns of the text messages, a linear SVM gets 97.9% in 4 milliseconds with no tuning. Its optimum is unique (the loss is convex, calculus 5), so there's no seed lottery.
Breaks: training compares pairs of points, so time grows roughly with the square of the rows. Measured on 10 columns: 2,000 rows 0.02 s, 4,000 rows 0.09 s, 8,000 rows 0.3 s, 16,000 rows 1.2 s. Each doubling multiplies the time by about 4, so a million rows would take hours where boosting takes seconds.
On the bank calls, the RBF SVM's AUC is 0.711, the lowest in the zoo (every other model reaches at least 0.74). Which reason fits best?
- The columns weren't scaled
- Too much data
- Its scores come from distances to the hardest cases, on a table of one-hot categories and skewed counts where distance means little
SVMs shine on clean, medium-sized, many-column data where distance means something; they're slow on big data, sensitive to scaling and γ, and give scores rather than probabilities.
Where it breaks, and what people do
- Big data. Kernel SVMs scale like rows squared or worse. For millions of rows use a linear SVM (
LinearSVC,SGDClassifier(loss="hinge")), or approximate the kernel with random features (RBFSampler,Nystroem) and fit a linear model on them. - γ and C. They interact, and the good region can be narrow (digits: 99.1% at γ = 0.001, 10% at 0.1). Search both on a log grid with cross-validation.
- Scaling. The RBF kernel is a distance, so unscaled columns hijack it, as on page 3 (bank calls: 0.677 unscaled, 0.711 scaled).
- No probabilities. The score \(f(x)\) is a signed distance, not a chance.
probability=Truefits a sigmoid on cross-validated scores (Platt scaling), which costs five extra fits and can disagree withpredict. - Tables. Mixed categories and counts: use boosted trees or logistic regression first.
5. The knobs that matter
| Knob | In scikit-learn | What it does |
|---|---|---|
| Kernel | kernel ("rbf", "linear", "poly") | Linear for many columns (text); RBF for a few dense ones (measurements, small images). |
| Soft margin | C | Small: wide street, many support vectors, smooth. Large: narrow street, fits every dot. Log grid, 0.01 to 1000. |
| Kernel width | gamma (default "scale" = 1 / (columns × variance)) | Small: nearly linear. Large: a bubble around each dot. Tune together with C. |
| Scaling | StandardScaler in a pipeline | Required for RBF and polynomial kernels. |
| Imbalance | class_weight | Raises C for the rare class. |
| Big data | LinearSVC, SGDClassifier(loss="hinge"), Nystroem | Linear time in rows instead of quadratic. |
Next in the zoo: the network from stage 2, judged as one more model for tables.
All chapters: AI from scratch. Digits: UCI optical recognition of handwritten digits, via scikit-learn.
Last updated