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?

γ sets how far a dot's influence reaches. At large γ, each dot is only similar to itself, so the boundary becomes a bubble around each training dot (memorizing), and every dot is needed to describe it. Measured on handwritten digits: γ = 0.001 gets 99.1% with half the training rows as support vectors; γ = 0.01, 79.6% with 99.5% of them; γ = 0.1, 10%, chance.

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?

\(\max(0, 1 - 3) = 0\): it contributes nothing to the loss and nothing to the gradient. The solution is the same with or without it. That sparsity is the SVM's signature, and on the bank calls it's a weakness too: the model ignores the bulk of easy cases and lives on the ambiguous ones.
Why the dual form enables the kernel trick
  1. 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\).
  2. 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\).
  3. 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 \]

  4. 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\).
  5. 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.
  6. 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?

An RBF kernel says "similar rows are near each other". For 63 one-hot and economic columns, nearness is a weak notion of similarity (the same problem kNN had on page 3), and the hinge loss throws away the easy cases that carry most of the calibration. Trees and linear models simply fit the table better. SVMs are for data where a distance means something: pixels, word counts, measurements on one scale.

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

5. The knobs that matter

KnobIn scikit-learnWhat it does
Kernelkernel ("rbf", "linear", "poly")Linear for many columns (text); RBF for a few dense ones (measurements, small images).
Soft marginCSmall: wide street, many support vectors, smooth. Large: narrow street, fits every dot. Log grid, 0.01 to 1000.
Kernel widthgamma (default "scale" = 1 / (columns × variance))Small: nearly linear. Large: a bubble around each dot. Tune together with C.
ScalingStandardScaler in a pipelineRequired for RBF and polynomial kernels.
Imbalanceclass_weightRaises C for the rare class.
Big dataLinearSVC, SGDClassifier(loss="hinge"), NystroemLinear 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