The Dual SVM and Kernels
The SVM's constrained problem has a dual in which the data appears only through inner products . Replace those inner products by a kernel 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 for the margin constraints (Lagrange Multipliers). Setting the derivatives of the Lagrangian with respect to and to zero gives
So the weight vector is a combination of training points. Substituting back leaves a problem in alone:
By complementary slackness, for points beyond the margin: only support vectors have . Predictions need only those:
The kernel trick
Map inputs to features and run the SVM there. The dual only needs . Some kernels are cheap to evaluate although their feature space is huge or infinite:
| Kernel | Feature space | |
|---|---|---|
| linear | the input itself | |
| polynomial | all monomials up to degree | |
| RBF (Gaussian) | infinite-dimensional |
A function is a valid kernel when every Gram matrix is symmetric positive semidefinite.
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 by subgradient descent on the hinge loss (a common primal approach):
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;gammais ;dual_coef_holds .- Kernel ridge regression and Gaussian processes use the same Gram matrices.
- For very large the 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
Candgammatogether.
Exercises
Exercise 1: Weight vector from the dual
Support vectors with , and with , . Compute and check .
Answer
; .
Solution
.
Exercise 2: Kernel value
Compute the RBF kernel with for , .
Answer
.
Solution
, so . Identical points give 1; distant points give nearly 0.
Exercise 3: Not a kernel (code)
Check whether gives a PSD Gram matrix on the points , and whether can be a kernel.
Answer
: PSD (a valid kernel). : not even symmetric.
Solution
is an inner product of with . The difference changes sign when the arguments swap.
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…
- the labels
- inner products
- the norms of the points
- the feature means
Which training points have in the dual solution?
- All of them
- The support vectors
- Only misclassified points
- None
A function is a valid kernel if…
- it is always positive
- every Gram matrix it produces is symmetric positive semidefinite
- it is linear
- it equals the Euclidean distance