TExcelTAD
Home › Math for Machine Learning › The Dual SVM and Kernels

The Dual SVM and Kernels

The SVM's constrained problem has a dual in which the data appears only through inner products xiTxj\mathbf{x}_i^T\mathbf{x}_j. Replace those inner products by a kernel k(xi,xj)k(\mathbf{x}_i, \mathbf{x}_j) and the same algorithm learns nonlinear boundaries, as if the data had been mapped into a huge feature space, without ever computing that map. This "kernel trick" is one of the most elegant ideas in ML.

Deriving the dual

For the soft-margin SVM, introduce multipliers αn≥0\alpha_n \ge 0 for the margin constraints (Lagrange Multipliers). Setting the derivatives of the Lagrangian with respect to w\mathbf{w} and bb to zero gives

w=∑n=1Nαnynxn,∑n=1Nαnyn=0\mathbf{w} = \sum_{n=1}^{N}\alpha_ny_n\mathbf{x}_n, \qquad \sum_{n=1}^{N}\alpha_ny_n = 0

So the weight vector is a combination of training points. Substituting back leaves a problem in α\boldsymbol{\alpha} alone:

max⁡α ∑nαn−12∑i∑jαiαjyiyj xiTxjs.t.0≤αn≤C,  ∑nαnyn=0\max_{\boldsymbol{\alpha}}\ \sum_{n}\alpha_n - \frac{1}{2}\sum_{i}\sum_{j}\alpha_i\alpha_jy_iy_j\,\mathbf{x}_i^T\mathbf{x}_j \quad \text{s.t.} \quad 0 \le \alpha_n \le C,\ \ \sum_n\alpha_ny_n = 0

By complementary slackness, αn=0\alpha_n = 0 for points beyond the margin: only support vectors have αn>0\alpha_n > 0. Predictions need only those:

f(x)=∑n∈SVαnyn xnTx+bf(\mathbf{x}) = \sum_{n \in \text{SV}}\alpha_ny_n\,\mathbf{x}_n^T\mathbf{x} + b

The kernel trick

Map inputs to features ϕ(x)\boldsymbol{\phi}(\mathbf{x}) and run the SVM there. The dual only needs ϕ(xi)Tϕ(xj)=k(xi,xj)\boldsymbol{\phi}(\mathbf{x}_i)^T\boldsymbol{\phi}(\mathbf{x}_j) = k(\mathbf{x}_i, \mathbf{x}_j). Some kernels are cheap to evaluate although their feature space is huge or infinite:

Kernel k(x,x′)k(\mathbf{x}, \mathbf{x}') Feature space
linear xTx′\mathbf{x}^T\mathbf{x}' the input itself
polynomial (xTx′+c)d(\mathbf{x}^T\mathbf{x}' + c)^d all monomials up to degree dd
RBF (Gaussian) exp⁡(−∥x−x′∥2/2ℓ2)\exp(-\lVert \mathbf{x} - \mathbf{x}' \rVert^2 / 2\ell^2) infinite-dimensional

A function is a valid kernel when every Gram matrix Kij=k(xi,xj)K_{ij} = k(\mathbf{x}_i, \mathbf{x}_j) is symmetric positive semidefinite.

python · try it yourself
import numpy as np

# degree-2 polynomial kernel equals an explicit 6-dimensional feature map
def phi(x):
    a, b = x
    return np.array([1, np.sqrt(2) * a, np.sqrt(2) * b, a * a, b * b, np.sqrt(2) * a * b])
x, z = np.array([1.0, 2.0]), np.array([3.0, -1.0])
print("kernel (x.z + 1)^2:", (x @ z + 1) ** 2, "  explicit phi(x).phi(z):", round(phi(x) @ phi(z), 10))
rng = np.random.default_rng(0)
P = rng.normal(size=(30, 2))
K = np.exp(-np.sum((P[:, None] - P[None]) ** 2, axis=2) / 2)          # RBF Gram matrix
print("RBF Gram matrix: symmetric", np.allclose(K, K.T), ", min eigenvalue", f"{np.linalg.eigvalsh(K).min():.2e}")
kernel (x.z + 1)^2: 4.0   explicit phi(x).phi(z): 4.0
RBF Gram matrix: symmetric True , min eigenvalue 8.82e-08

A kernel classifier from scratch

A circle-shaped class boundary is impossible for a linear classifier but easy with an RBF kernel. Instead of a full dual QP solver, we fit a kernel model f(x)=∑nβnk(xn,x)+bf(\mathbf{x}) = \sum_n\beta_nk(\mathbf{x}_n, \mathbf{x}) + b by subgradient descent on the hinge loss (a common primal approach):

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
X = rng.uniform(-2, 2, size=(200, 2))
y = np.where(np.sum(X**2, axis=1) < 1.5, 1.0, -1.0)            # inside a circle = +1
def rbf(A, B, ell=0.7): return np.exp(-np.sum((A[:, None] - B[None]) ** 2, axis=2) / (2 * ell**2))
K = rbf(X, X)
beta, b, lam, lr = np.zeros(200), 0.0, 1e-3, 0.05
for _ in range(1500):
    f = K @ beta + b
    active = y * f < 1
    g_beta = lam * (K @ beta) - (K[:, active] @ y[active]) / len(y)
    g_b = -y[active].sum() / len(y)
    beta -= lr * g_beta; b -= lr * g_b
X_test = rng.uniform(-2, 2, size=(1000, 2)); y_test = np.where(np.sum(X_test**2, axis=1) < 1.5, 1.0, -1.0)
acc_k = np.mean(np.sign(rbf(X_test, X) @ beta + b) == y_test)
w = np.linalg.lstsq(np.column_stack([X, np.ones(200)]), y, rcond=None)[0]       # a linear baseline
acc_l = np.mean(np.sign(np.column_stack([X_test, np.ones(1000)]) @ w) == y_test)
print(f"RBF kernel accuracy {acc_k:.3f}   linear baseline accuracy {acc_l:.3f}")
RBF kernel accuracy 0.964   linear baseline accuracy 0.702

The linear model can do little better than always guessing the majority class; the kernel model learns the circle.

In software

  • sklearn.svm.SVC(kernel="rbf", C=..., gamma=...) solves the dual with libsvm; gamma is 1/(2ℓ2)1/(2\ell^2); dual_coef_ holds αnyn\alpha_ny_n.
  • Kernel ridge regression and Gaussian processes use the same Gram matrices.
  • For very large NN the N×NN \times N Gram matrix is too big; random Fourier features approximate the RBF kernel with an explicit finite map.

Go further: Kernel SVMs: RBF, C and gamma rebuilds scikit-learn's decision function from the dual coefficients and tunes C and gamma together.

Exercises

Exercise 1: Weight vector from the dual

Support vectors (1,2)(1, 2) with α=0.5\alpha = 0.5, y=+1y = +1 and (2,0)(2, 0) with α=0.5\alpha = 0.5, y=−1y = -1. Compute w\mathbf{w} and check ∑nαnyn=0\sum_n\alpha_ny_n = 0.

Answer

w=(−0.5,1)\mathbf{w} = (-0.5, 1); 0.5−0.5=00.5 - 0.5 = 0.

Solution

w=0.5⋅(1,2)−0.5⋅(2,0)=(0.5−1,1−0)=(−0.5,1)\mathbf{w} = 0.5 \cdot (1, 2) - 0.5 \cdot (2, 0) = (0.5 - 1, 1 - 0) = (-0.5, 1).

Exercise 2: Kernel value

Compute the RBF kernel with ℓ=1\ell = 1 for x=(0,0)\mathbf{x} = (0, 0), x′=(1,1)\mathbf{x}' = (1, 1).

Answer

e−1≈0.368e^{-1} \approx 0.368.

Solution

∥x−x′∥2=2\lVert \mathbf{x} - \mathbf{x}' \rVert^2 = 2, so k=exp⁡(−2/2)=e−1k = \exp(-2/2) = e^{-1}. Identical points give 1; distant points give nearly 0.

Exercise 3: Not a kernel (code)

Check whether k(x,x′)=cos⁡(x−x′)k(x, x') = \cos(x - x') gives a PSD Gram matrix on the points 0,1,20, 1, 2, and whether k(x,x′)=x−x′k(x, x') = x - x' can be a kernel.

Answer

cos⁡(x−x′)\cos(x - x'): PSD (a valid kernel). x−x′x - x': not even symmetric.

Solution

cos⁡(x−x′)=cos⁡xcos⁡x′+sin⁡xsin⁡x′\cos(x - x') = \cos x\cos x' + \sin x\sin x' is an inner product of (cos⁡x,sin⁡x)(\cos x, \sin x) with (cos⁡x′,sin⁡x′)(\cos x', \sin x'). The difference x−x′x - x' changes sign when the arguments swap.

python · try it yourself
import numpy as np
p = np.array([0.0, 1.0, 2.0])
K1 = np.cos(p[:, None] - p[None]); K2 = p[:, None] - p[None]
print(np.round(np.linalg.eigvalsh(K1), 6) + 0, np.allclose(K2, K2.T))
[0.       1.416147 1.583853] False

Test yourself

In the dual SVM, the data appears only through…

  1. the labels
  2. inner products xiTxj\mathbf{x}_i^T\mathbf{x}_j
  3. the norms of the points
  4. the feature means

Which training points have αn>0\alpha_n > 0 in the dual solution?

  1. All of them
  2. The support vectors
  3. Only misclassified points
  4. None

A function kk is a valid kernel if…

  1. it is always positive
  2. every Gram matrix it produces is symmetric positive semidefinite
  3. it is linear
  4. it equals the Euclidean distance