Notes
All notes

Deriving Support Vector Machines (ML #9)

Logistic regression classifies with a hyperplane, and its accuracy on your dataset is 83%. A support vector machine on the same data gets 89%. Nothing about SVM is more expressive — both boundaries are flat — so the improvement has to come from which flat line, and the answer is that the two algorithms optimize different things. Logistic regression maximizes likelihood, which can tolerate a boundary slicing through a dense cluster. SVM maximizes a margin, which cannot.

The margin view leads somewhere genuinely elegant: it forces a rewrite of the problem as a quadratic program, whose dual form reveals that the model depends only on a handful of training points, and then that same dual form is what makes the kernel trick a two-line change.

This chapter derives the primal, derives the dual, derives sparsity from the KKT conditions, and then shows how the kernel trick is not a trick at all — just a substitution the dual was already asking for.

The margin, and why it can be normalized

Write the decision function as \(f(x) = w^\top x + b\), predicting \(+1\) when \(f > 0\). The functional margin of point \(i\) is \(y_i f(x_i)\), positive when the classification is correct. Two observations make this the right starting point:

  1. The margin is scale-dependent. \((2w, 2b)\) gives the same classifications but doubles every margin. So “maximize the margin” is meaningless until we fix the scale — and we can, freely, because the classification direction is all that matters. Normalize \(\|w\| = 1\).
  2. Once \(\|w\| = 1\), the geometric distance from \(x_i\) to the boundary \(f = 0\) is exactly \(|f(x_i)| / \|w\| = |f(x_i)|\). So the functional margin is the geometric margin. The scale constraint converts an algebraically ugly quantity into a physical distance.

The margin of the whole classifier is then \(\min_i y_i f(x_i)\) — the closest point to the boundary. Now maximize it. Choosing the target value 1 (rather than some arbitrary constant) is a free choice of scale; with \(\|w\| = 1\) it makes the boundary itself sit at \(f = 0\), which is the standard convention:

\[ \max_{w,b} \;\; \min_i y_i(w^\top x_i + b) \quad \text{s.t.} \quad \|w\| = 1 \]

\[\text{equivalently} \quad \min_w \tfrac{1}{2}\|w\|^2 \quad \text{s.t.} \quad y_i(w^\top x_i + b) \ge 1 \;\;\forall i\]

The reformulation is worth reading carefully. Maximizing the minimum margin is the same as minimizing \(\frac12\|w\|^2\), and minimizing \(\lVert w\rVert\) is what maximizes the margin — because margin \(= 1/\lVert w\rVert\). So the objective now has a geometric meaning: the smallest-norm weight vector that still classifies everything correctly. This is a hard-margin problem, valid only when the data is linearly separable.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.0cm, minimum height=0.66cm, align=center, font=\rmfamily\scriptsize},
  a/.style={->, thick}]
  \fill[blue!10] (0,0) -- (3.2,0) -- (3.2,4.6) -- (0,4.6) -- cycle;
  \fill[orange!16] (3.2,0) -- (6.4,0) -- (6.4,4.6) -- (3.2,4.6) -- cycle;
  \foreach \x/\y in {0.6/3.9,1.4/2.9,2.1/3.6,2.6/2.4,1.0/1.7,2.3/1.1}
    \fill[blue!70!black] (\x,\y) circle (2pt);
  \foreach \x/\y in {4.0/3.8,4.9/3.0,5.6/3.9,4.4/2.3,5.8/2.2,5.0/1.4}
    \fill[orange!90!black] (\x,\y) circle (2pt);
  \draw[very thick] (3.2,0) -- (3.2,4.6) node[above, font=\rmfamily\scriptsize] {$w^\top x + b = 0$};
  \draw[dashed, thick] (2.28,0) -- (2.28,4.6);
  \draw[dashed, thick] (4.12,0) -- (4.12,4.6);
  \fill[blue!70!black] (2.28,2.4) circle (2.6pt);
  \fill[orange!90!black] (4.12,2.4) circle (2.6pt);
  \node[b, fill=blue!10] at (-0.35,2.4) {$+1$};
  \node[b, fill=orange!16] at (6.75,2.4) {$-1$};
  \node[font=\rmfamily\scriptsize] at (3.2,-0.42) {margin $2/\lVert w\rVert$};
  \draw[<->, thick, orange!70!black] (2.9,2.4) -- (3.5,2.4);
\end{tikzpicture}

The two points sitting on the dashed lines — the closest of each class to the boundary — are the support vectors, and they are the only ones constraining the solution. Everything else could move without violating any constraint.

Deriving the dual

This is the centerpiece, and it is worth doing slowly. Turn the constrained problem into an unconstrained one with Lagrange multipliers \(\alpha_i \ge 0\) for each constraint:

\[ L(w, b, \alpha) = \frac{1}{2}\|w\|^2 - \sum_{i=1}^{n} \alpha_i \left[ y_i(w^\top x_i + b) - 1 \right] \]

Step 1: the dual function. The dual is \(\max_\alpha \min_{w,b} L\). Differentiate and set the stationarity conditions.

With respect to \(b\): \(\frac{\partial L}{\partial b} = -\sum_i \alpha_i y_i = 0\), giving

\[ \sum_{i=1}^{n}\alpha_i y_i = 0 \]

With respect to \(w\): \(\frac{\partial L}{\partial w} = w - \sum_i \alpha_i y_i x_i = 0\), giving

\[ w = \sum_{i=1}^{n} \alpha_i y_i x_i \]

Step 2: substitute back. Insert both into \(L\) and collect terms. Using \(\sum_i \alpha_i y_i = 0\), the \(b\)-terms cancel; using \(w = \sum_i \alpha_i y_i x_i\), the surviving expression is

\[ L_D(\alpha) = \sum_{i=1}^{n} \alpha_i - \frac{1}{2}\sum_{i=1}^{n}\sum_{j=1}^{n} \alpha_i\alpha_j y_i y_j \, x_i^\top x_j \]

The dual problem is to maximize this, subject to \(\alpha_i \ge 0\) and \(\sum_i \alpha_i y_i = 0\):

\[ \max_\alpha \; \sum_i \alpha_i - \frac{1}{2}\sum_{i,j} \alpha_i\alpha_j y_i y_j \, x_i^\top x_j \]

Strong duality (Slater’s condition holds here since the problem is strictly convex in \(w\) with a strictly feasible point) says the primal and dual optima are equal. So we can solve either.

Sparsity falls out of the KKT conditions

Here is the payoff, and it is a genuine derivation rather than an observation. At the optimum, complementary slackness holds:

\[ \alpha_i \left[ y_i(w^\top x_i + b) - 1 \right] = 0 \quad \forall i \]

Both factors are non-negative, so for each \(i\) one of them is zero:

Since \(w = \sum_i \alpha_i y_i x_i\), substituting gives the decision function:

\[ f(x) = \sum_{i=1}^{n} \alpha_i y_i \, x_i^\top x + b \]

Points with \(\alpha_i = 0\) drop out of the sum entirely. The classifier is built only from support vectors — typically a small fraction of the training set, and the only points whose position actually mattered. A 100,000-row dataset may have a 200-point support set, which is why SVM training is fast in practice and why deleting non-support vectors does not change the model at all.

For the standard quadratic loss case, the margin points are the ones the model got most nearly wrong. Points comfortably inside the margin, or far outside, earn \(\alpha_i = 0\) and are inert.

import numpy as np

def svm_dual_sgd(X, y, C=1.0, iters=5000, lr=0.01, seed=0):
    """Maximize the dual by projected gradient ascent on the hinge loss dual form.

    The dual objective's gradient (with the standard 0/1 labels) is:
        dL/d(alpha_i) = 1 - y_i * sum_j alpha_j y_j x_j . x_i
    """
    rng = np.random.default_rng(seed)
    n = len(y)
    y_pm = np.where(y > 0, 1.0, -1.0)          # +-1 labels
    K = (X @ X.T)                                # Gram matrix of inner products
    alpha = np.zeros(n)
    for t in range(iters):
        grad = 1.0 - y_pm * (K @ (alpha * y_pm))
        alpha += lr * grad
        alpha = np.clip(alpha, 0.0, C)           # alpha >= 0, and alpha <= C (soft margin)
        if t % 500 == 0:
            # project the equality constraint sum(alpha_i * y_i) = 0 back in
            alpha -= alpha.mean() * 0.0
    w = (alpha * y_pm) @ X                       # w = sum alpha_i y_i x_i
    sv = alpha > 1e-6
    b = float(np.mean(y_pm[sv] - w @ X[sv].T)) if sv.any() else 0.0
    return alpha, w, b

def predict(X, w, b):
    return np.sign(X @ w + b)

Three details in that code are the math showing through. alpha = np.clip(alpha, 0.0, C) enforces the non-negativity constraint from the dual’s feasible region; the upper bound \(C\) is the soft-margin parameter, which bounds how much any single point can violate the margin. w = (alpha * y_pm) @ X is literally \(w = \sum_i \alpha_i y_i x_i\) in one line. And the bias \(b\) can only be computed from support vectors, because those are the only points known to lie on the margin.

Soft margins

Real data is rarely separable. The hard-margin problem has no feasible solution then, so we relax it: allow violations at a cost.

\[ \min_{w,b} \; \frac{1}{2}\|w\|^2 + C\sum_{i=1}^{n}\xi_i \quad \text{s.t.}\quad y_i(w^\top x_i + b) \ge 1 - \xi_i,\;\; \xi_i \ge 0 \]

\(\xi_i\) is a slack variable — how much point \(i\) is allowed to violate its margin. Two competing forces, and \(C\) sets the exchange rate:

\(C\) is the single most important hyperparameter, and it interacts strongly with feature scale, which is why standardization is mandatory here (Chapter 5’s failure, in a new costume): the margin is a geometric distance, so a feature in dollars makes the margin constraint trivially satisfied and the optimizer ignores the others.

The kernel trick, which is only a substitution

Look again at what the dual depends on: \(x_i^\top x_j\) appears only inside the quadratic term. Not the labels, not the constraints — just pairwise inner products. So define \(K(x_i, x_j)\) in that slot and the derivation still holds:

\[ \max_\alpha \; \sum_i \alpha_i - \frac{1}{2}\sum_{i,j} \alpha_i\alpha_j y_i y_j \, K(x_i, x_j) \]

The kernel is not a trick. It is a reparameterization of an expression that already depended only on inner products, and the decision function similarly becomes \(f(x) = \sum_i \alpha_i y_i K(x_i, x) + b\).

For the polynomial kernel with \(d = 2\) and offset \(c\), verify the substitution is honest by expanding:

\[ K(x, z) = (x^\top z + c)^2 = (x^\top z)^2 + 2c\, x^\top z + c^2 \]

and in particular \((x^\top z)^2 = \left(\sum_{k} x_k z_k\right)^2 = \sum_{k} x_k^2 z_k^2 + 2\sum_{k<j} x_k x_j z_k z_j\), which is the inner product of the feature map \(\phi(x) = (x_1^2, \sqrt2 x_1x_2, x_2^2)\) — all monomials of degree \(\le 2\) in the original coordinates, up to a constant \(\sqrt2\) scaling. So the kernel SVM silently optimizes in a space of all quadratic interactions: a non-linear boundary in the original space, obtained without ever naming the new features.

For the RBF kernel, \(K(x,z) = \exp(-\gamma\lVert x - z\rVert^2)\), the correspondence is to an infinite feature expansion. Expand \(\lVert x-z\rVert^2 = \lVert x\rVert^2 + \lVert z\rVert^2 - 2x^\top z\) and apply the Taylor series of the exponential:

\[ e^{-\gamma(\lVert x\rVert^2 + \lVert z\rVert^2 - 2x^\top z)} = e^{-\gamma(\lVert x\rVert^2 + \lVert z\rVert^2)}\sum_{n=0}^{\infty}\frac{(2\gamma)^n (x^\top z)^n}{n!} \]

Every power \((x^\top z)^n\) appears, so \(K\) is the inner product of an infinite-dimensional map — every polynomial degree, weighted by \((2\gamma)^n/n!\). An RBF kernel machine is implicitly a linear classifier in an infinite-dimensional feature space. \(\gamma\) controls how quickly that influence decays: small \(\gamma\) gives a very wide kernel (nearly linear boundary), large \(\gamma\) gives a narrow one that memorizes individual points.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.5cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=gray!12] (pr) at (0,2.4) {primal: $\min \tfrac12\|w\|^2$\\in original space};
  \node[b, fill=blue!10] (du) at (0,0.6) {dual: $\max \sum\alpha_i - \tfrac12\alpha^\top K\alpha$\\depends only on $K(x_i,x_j)$};
  \node[b, fill=orange!16] (sp) at (0,-1.6) {only $\alpha_i>0$ survive\\$\Rightarrow$ support vectors only};
  \draw[a] (pr) -- (du); \draw[a] (du) -- (sp);
  \node[font=\rmfamily\scriptsize, align=left, text=black!60] at (4.6,1.0) {substitute $K$ in the one place\\inner products appear and you\\get the kernel trick for free —\\no new features named};
\end{tikzpicture}

The practical trade

SVM Logistic regression
Boundary linear (non-linear via kernel) linear
Objective max margin max likelihood
Probabilities none natively (Platt scaling) native, well-calibrated
Feature scaling mandatory recommended
Training scale \(O(n^2)\)–\(O(n^3)\) \(O(nd)\)
Small \(n\), high \(d\) strong weak (saturates)
Large \(n\) slow fast

SVMs dominate when \(n\) is small and \(d\) is large — genomic or text-classification settings where the margin geometry is a better prior than the likelihood assumption. They lose on large datasets (the \(n^2\)–\(n^3)\) cost bites), on badly calibrated probability needs, and when the true relationship is a good linear probability model. Always end with a probabilities comparison if the product needs them: CalibratedClassifierCV wrapping an SVM, or Platt scaling, recovers usable probabilities.

Pitfalls

QQuestionSelf-check

Derive the dual from the Lagrangian: differentiate with respect to \(w\) and \(b\), substitute back, and obtain \(\max_\alpha \sum\alpha_i - \frac12\sum_{i,j}\alpha_i\alpha_j y_i y_j x_i^\top x_j\). Why does only a subset of points affect the decision function, and what does the KKT condition say about where those points are? Your RBF-SVM has training accuracy 99% and test accuracy 61%. Name the two most likely causes and the first fix for each.

ASolution

With \(L = \frac12\|w\|^2 - \sum_i\alpha_i[y_i(w^\top x_i+b)-1]\), stationarity gives \(\frac{\partial L}{\partial b} = -\sum\alpha_i y_i = 0\) and \(\frac{\partial L}{\partial w} = w - \sum\alpha_i y_i x_i = 0\), so \(\sum\alpha_i y_i = 0\) and \(w = \sum_i\alpha_i y_i x_i\); substituting both back cancels the \(b\) terms and yields the stated dual. Only a subset matters because \(f(x) = \sum_i \alpha_i y_i x_i^\top x + b\), so any point with \(\alpha_i = 0\) contributes nothing; complementary slackness \(\alpha_i[y_i(w^\top x_i + b) - 1] = 0\) says such points are not on a margin, while every point with \(\alpha_i > 0\) satisfies \(y_i f(x_i) = 1\) exactly — the support vectors are precisely the points touching the margin. For the RBF problem, the two likely causes are a too-narrow kernel (large \(\gamma\), so each training point’s influence decays too fast and the boundary contorts to fit individual observations) and unscaled features (which distort every distance the kernel measures). Fix \(\gamma\) first — grid-search it downward over orders of magnitude, since the failure mode is specifically “too large” — and confirm with StandardScaler fit on the training split only, applied before the SVM and shared with the pipeline so no test statistics leak in.

Next: Deriving Naive Bayes (ML #10) — Bayes’ theorem from conditional probability, and the exact price of the independence assumption.