Lesson 33 · 100 min · core
Kernel Methods & Support Vector Machines
The support vector machine (SVM) chooses, among all hyperplanes that separate two classes, the one with the largest margin. This lesson derives the distance from a point to a hyperplane and the margin , formulates the hard- and soft-margin primal problems, derives the Lagrangian dual term by term, reads off from the KKT conditions which training points become support vectors and how the bias is recovered, and shows that both training and prediction touch the data only through inner products. Replacing the inner product by a kernel gives non-linear classifiers at the cost of a linear one: we construct the explicit feature maps of the polynomial kernel and of the Gaussian (RBF) kernel, whose feature space is infinite-dimensional, and prove that every Gram matrix of a kernel is symmetric positive semidefinite, the property that quantum kernels will inherit in Module 3.3.
Prerequisites: Supervised Learning & Gradient Descent, Inner Products, Norms & Gram–Schmidt
Objectives and key results
Derive the distance from a point to the hyperplane and the margin width of a canonical separating hyperplane.
Formulate the hard-margin primal s.t. and the soft-margin primal with slacks and penalty , and identify the latter as hinge-loss regularised risk minimisation.
Derive the dual subject to and from the Lagrangian, including every substitution step.
Use KKT complementary slackness to classify training points (, , ) and to recover the bias from free support vectors.
Apply the kernel trick and write the explicit feature maps of the polynomial kernel and of the RBF kernel .
Prove that the Gram matrix of every kernel is symmetric positive semidefinite, and compute and validate an RBF Gram matrix in code.
- formula · Margin of a canonical hyperplane
- formula · Soft-margin SVM dual
- theorem · Support vectors from complementary slackness
- identity · Kernelised decision function
- identity · RBF feature map
- theorem · Gram matrices are PSD
Linear classifiers and the maximum margin#
We are given a training set with inputs and binary labels . A linear classifier is the function with weight vector and bias ; it predicts . In the language of the previous lesson this is empirical risk minimisation over the hypothesis class of affine functions, but with the 0–1 loss the risk is piecewise constant in and gradient descent has nothing to follow. The SVM replaces "any separating hyperplane" by a geometric criterion, the margin, which leads to a convex quadratic program with a unique optimal .
Definition
Separating hyperplane
The hyperplane of is . The data are linearly separable if some satisfies for every , i.e. every point lies strictly on the side of given by its label. The number is the functional margin of point ; it is positive exactly when the point is classified correctly.
Distance from a point to a hyperplane
For and any , and the minimum is attained at the orthogonal projection . If carries the label and is correctly classified, the distance equals .
Proof (7 steps)
- Step 1:Subtract the two defining equations: is orthogonal to every vector lying inside the hyperplane, i.e. is a normal vector of .
- Step 2:Insert the definition of and use .
- Step 3:Expand the squared norm of a sum for an arbitrary .
- Step 4:is a multiple of , and lies inside the hyperplane (both and do), so step 1 applies.
- Step 5:Pythagoras: the cross term vanishes, and with equality only at .
- Step 6:Norm of the scalar multiple .
- Step 7:and correct classification means has the sign of .
∎
Definition
Geometric margin
For a separating the geometric margin of point is , its distance to the hyperplane, and the margin of the classifier on the training set is . The maximum-margin hyperplane maximises over all separating .
From maximum margin to the hard-margin primal
- Step 1:Rescaling by a positive factor does not move the hyperplane and does not change the margin, so we may fix the scale.
- Step 2:For a separating hyperplane the minimum functional margin is positive, so this exists. A pair with is called canonical.
- Step 3:Definition of the geometric margin with the normalisation of the previous step.
- Step 4:The closest points of the two classes lie on the parallel hyperplanes . Take any with and apply the distance formula to the hyperplane : the empty band between the classes has width .
- Step 5:Any satisfying these constraints (canonical or not) has every ; for the canonical rescaling of a separating pair equality holds. Hence .
- Step 6:is decreasing and is increasing on , so all three problems have the same minimisers. The square makes the objective differentiable and the factor cancels the of its gradient.
Result
Quick check
A canonical separating hyperplane has . What is the width of the margin band? Give a decimal.
Soft margins and slack variables#
Real data are rarely separable, and when they are, a single outlier can force a tiny margin. The soft-margin SVM (Cortes and Vapnik, 1995) allows each constraint to be violated by a slack and pays for it. The constant sets the trade-off between a wide margin (small ) and few violations (small ).
Definition
Soft-margin primal problem
The problem is always feasible: , , satisfies every constraint. Its objective is convex and its constraints are affine, so it is again a convex quadratic program.
Eliminating the slacks: the hinge loss
- Step 1:The two constraints on are two lower bounds; together they say exceeds their maximum.
- Step 2:For fixed the objective is strictly increasing in each (coefficient ), so each slack sits at its lower bound.
- Step 3:Substitute the optimal slacks: the primal is equivalent to this unconstrained problem.
- Step 4:Factor out , which does not change the minimiser: the soft-margin SVM is regularised empirical risk minimisation with the hinge loss, a convex upper bound of the 0–1 loss.
- Step 5:A misclassified point has non-positive functional margin, hence slack at least ; summing, the total slack bounds the number of training errors.
The optimal slack classifies every training point: when (on or beyond its margin hyperplane), when the point is inside the band but on the correct side, and when it is misclassified. Large makes violations expensive; on separable data, as the soft-margin solution approaches the hard-margin one. Small tolerates many violations in exchange for a wider band, which is the main defence against overfitting noisy labels.
The Lagrangian dual#
Following Boyd and Vandenberghe (§5.1), write each constraint as , attach a non-negative multiplier to it and add it to the objective. The multipliers are for and for . The dual function is a lower bound on the primal optimum for every (weak duality), because on any feasible point the added terms are . The dual problem maximises this lower bound.
Derivation of the soft-margin dual
- Step 1:Objective plus multiplier times constraint function: and .
- Step 2:Expand the bracket and collect the terms in , in , in each , and the constant .
- Step 3:A linear function of is bounded below only if its slope is zero. Stationarity in : .
- Step 4:Same argument for each slack: .
- Step 5:The multiplier only appears through this equation, so it can be eliminated; its sign constraint turns into the box constraint .
- Step 6:is a strictly convex quadratic in (Hessian ), so the unique stationary point is its global minimiser: the optimal weight vector is a linear combination of training inputs.
- Step 7:First term after substitution: expand the inner product bilinearly.
- Step 8:Second term: the vector in brackets is itself, so the term equals , i.e. twice the first term.
- Step 9:Third and fourth terms vanish on the set where the dual function is finite (steps 3 and 4).
- Step 10:Add the four terms and the constant ; , and have disappeared.
- Step 11:The quadratic form is a squared norm, so it is convex in and is concave: the dual is a concave maximisation (a convex QP) over the compact set .
Result
Strong duality for the soft-margin SVM
The primal and dual optimal values are equal and both are attained. Consequently a primal-feasible and a dual-feasible are both optimal if and only if they satisfy the KKT conditions of the next section.
Proof (5 steps)
- Step 1:and : the primal feasible set is a non-empty polyhedron.
- Step 2:A convex quadratic function bounded below (here by ) on a non-empty polyhedron attains its infimum (Frank–Wolfe theorem).
- Step 3:The dual feasible set contains and is closed and bounded; is continuous, so Weierstrass' theorem gives a maximiser.
- Step 4:Weak duality: for feasible primal points and the multiplier terms in are , so primal objective.
- Step 5:The objective is convex and every constraint is affine, so the refined Slater condition reduces to feasibility, which holds by step 1; Slater's theorem (Boyd and Vandenberghe §5.2.3) gives a zero duality gap.
∎
KKT conditions and support vectors#
KKT conditions of the soft-margin SVM
Let be primal feasible and . Both are optimal if and only if (stationarity) , , , and (complementary slackness)
Proof (6 steps)
- Step 1:() Optimality of both together with strong duality; the infimum is at most the value at the particular point .
- Step 2:The objective at the optimal primal point is ; each bracket and each is by feasibility and the multipliers are .
- Step 3:Steps 1 and 2 squeeze between and .
- Step 4:A sum of non-negative terms is zero only if every term is zero: complementary slackness. Since attains its infimum at (steps 1–3) and is finite, the stationarity equations of the dual derivation hold.
- Step 5:() If stationarity holds, is a stationary point of the convex function , hence a global minimiser.
- Step 6:By complementary slackness the multiplier terms of vanish, so the dual value equals the primal objective; weak duality then forces both to be optimal.
∎
Which points are support vectors
At an optimum, with : (i) ; (ii) , the point lies exactly on its margin hyperplane; (iii) , the point is on, inside or beyond the margin. Conversely and . The points with are the support vectors; only they enter .
Proof (6 steps)
- Step 1:(i) Stationarity , then , then primal feasibility.
- Step 2:(ii) Both complementary-slackness equations are active: the bracket must vanish and the slack is zero.
- Step 3:(iii) The first complementary-slackness equation with ; now leaves free to be positive.
- Step 4:Converse 1: the bracket is strictly positive because , so its multiplier vanishes.
- Step 5:Converse 2: feasibility forces positive slack, forces , and stationarity gives .
- Step 6:Terms with drop out: points strictly outside the margin can be deleted without changing the classifier.
∎
Recovering the bias from free support vectors
- Step 1:Case (ii) of the corollary for a free support vector .
- Step 2:Multiply by and use .
- Step 3:Solve for and insert .
- Step 4:Every free support vector gives the same in exact arithmetic; averaging over all of them reduces round-off. If is empty, every in the interval allowed by the bound vectors is optimal and SMO takes the midpoint.
Quick check
After training, a point has and slack . Where does it lie?
The kernel trick#
Look again at the result of the dual derivation and at the classifier it produces. The dual objective contains the inputs only through the numbers . The decision function is , which needs only , and the bias formula needs only . Nothing in training or prediction ever uses a coordinate of on its own. So if we first send the data through a map into a (possibly huge) inner-product space and run the linear SVM there, we only have to be able to evaluate , never itself.
Definition
Kernel and feature map
A function is a kernel if there are a real Hilbert space (the feature space) and a map (the feature map) with The linear kernel has . The feature map is not unique: followed by any isometry of gives the same .
The kernelised SVM
Running the soft-margin SVM on gives the dual of the previous section with replaced by , the optimal weight , and the decision function This holds even when is infinite-dimensional.
Proof (6 steps)
- Step 1:The Lagrangian is the same expression with replaced by and linearity of the inner product used to collect the terms.
- Step 2:Complete the square, valid in any inner-product space; no derivatives or coordinates are needed, so the minimisation over is exact even in infinite dimension.
- Step 3:Bilinearity of the inner product and the definition of the kernel.
- Step 4:The , and steps are unchanged; insert the minimum of the part.
- Step 5:With , the decision function needs kernel evaluations and no coordinate of .
- Step 6:The bias derivation for a free support vector, with the same substitution.
∎
XOR is not linearly separable
- Step 1:The XOR pattern: the label is the product of the coordinates.
- Step 2:Suppose separates the data. Both positive points need ; add the two inequalities.
- Step 3:Both negative points need ; add those two inequalities.
- Step 4:Contradiction, so no linear classifier on is correct on all four points.
- Step 5:After adding the single product feature, the hyperplane in separates the data with for all four points: a non-linear boundary in input space.
Feature map of the polynomial kernel
For and an integer , on is a kernel with the finite feature map indexed by multi-indices with : The feature space has dimension , while one evaluation of costs operations.
Proof (6 steps)
- Step 1:Write the base as a sum of terms , .
- Step 2:Multinomial theorem: expanding the -fold product, the monomial arises from choosing which of the factors contribute each , in ways.
- Step 3:Each splits into an part and an part.
- Step 4:The coefficient is non-negative because , so it has a real square root that can be shared equally between the factor and the factor.
- Step 5:Sum over all multi-indices: the kernel is the Euclidean inner product of the vectors .
- Step 6:Stars and bars: distributing identical units over slots. For , , this gives with .
∎
The degree-2 polynomial kernel contains the coordinate , so it separates XOR exactly as the hand-made map above. For and its feature space has dimensions, yet each kernel value is one inner product of length , one addition and two multiplications. This is the kernel trick: the cost of the SVM depends on (through the Gram matrix) and on the cost of evaluating , never on . A quantum feature map on qubits is the extreme case: , and the kernel is estimated by a circuit.
Quick check
What is the dimension of the feature space of the kernel on ?
The RBF kernel and its infinite-dimensional feature map#
Definition
Gaussian (RBF) kernel
For the Gaussian or radial basis function (RBF) kernel on is It depends only on the squared distance, equals on the diagonal and decays to for distant points. It is often written , i.e. with length scale . Multi-index notation: for , , and .
Explicit feature map of the RBF kernel
In one dimension, with In dimensions, with . Every is a unit vector of the sequence space , and the series is the inner product, so is a kernel with feature space .
Proof (9 steps)
- Step 1:Expand the squared norm of a difference.
- Step 2:. The first two factors each depend on one argument only; all coupling sits in .
- Step 3:Taylor series , which converges absolutely for every real .
- Step 4:In one dimension and the positive coefficient is split by its square root.
- Step 5:Multiply the series of step 4 by the two prefactors of step 2 and absorb one prefactor into each bracket.
- Step 6:dimensions: multinomial theorem with the terms , and .
- Step 7:The cancels. Regrouping the double sum into one sum over is allowed because the series of absolute values, , is finite.
- Step 8:Multiply by the two prefactors of step 2 and split each coefficient by its square root: this is .
- Step 9:Step 7 with (so ): is square-summable with norm , hence an element of , and by Cauchy–Schwarz the series in step 8 is the convergent inner product .
∎
No finite feature space reproduces the RBF kernel
Let . For any distinct points the vectors are linearly independent and the Gram matrix is positive definite. Consequently there is no feature map with for any finite .
Proof (6 steps)
- Step 1:A vector of is zero iff every coordinate is zero; keep the first coordinates.
- Step 2:Divide coordinate by the positive constant .
- Step 3:The system is the transpose of the Vandermonde matrix, whose determinant is non-zero for distinct nodes.
- Step 4:An invertible matrix has trivial kernel, and .
- Step 5:The Gram-matrix identity proved in the next section, with strict inequality because the combination is non-zero by linear independence.
- Step 6:A finite feature map would make (rows of ) of rank at most , contradicting positive definiteness for distinct points.
∎
Quick check
Compute for , and . Give a decimal.
Gram matrices are symmetric positive semidefinite#
Definition
Gram matrix
For a kernel and points the Gram matrix (kernel matrix) is with . A real matrix is positive semidefinite (PSD), , if it is symmetric and for every .
The Gram matrix of a kernel is symmetric positive semidefinite
If for a real Hilbert space , then for all and all the Gram matrix satisfies and for every . Equivalently, all eigenvalues of are real and non-negative.
Proof (6 steps)
- Step 1:A real inner product is symmetric.
- Step 2:Write the quadratic form entrywise.
- Step 3:The inner product is linear in each argument, so the double sum moves inside.
- Step 4:The inner product of a vector with itself is its squared norm, which is non-negative.
- Step 5:is real symmetric, so the spectral theorem gives an orthonormal eigenbasis with real eigenvalues; take in step 4.
- Step 6:Consequence for SMO: the curvature of the dual along a two-variable update is a value of the PSD quadratic form, so the pair subproblem is concave. The SVM dual's quadratic term is concave for the same reason.
∎
The theorem has a practical reading in both directions. Every kernel produces PSD Gram matrices: the linear, polynomial and RBF kernels above, and the quantum fidelity kernels of Module 3.3. Contrapositively, a symmetric function whose Gram matrix on some finite set has a negative eigenvalue cannot be written as an inner product of features. For example, on two points at distance gives with eigenvalues , so it is not a kernel. The converse statement, that every symmetric function with PSD Gram matrices on all finite sets is a kernel, is the Moore–Aronszajn theorem of the next lesson.
Worked example: an RBF Gram matrix on three points
- Step 1:Squared Euclidean distances, coordinate by coordinate.
- Step 2:with exponents , , ; the diagonal is . This is the visible test of the lab.
- Step 3:Leading principal minors of order 1 and 2.
- Step 4:Determinant of a symmetric matrix with unit diagonal and off-diagonal entries , , , by the rule of Sarrus.
- Step 5:Add the exponents. All leading principal minors are positive, so is positive definite by Sylvester's criterion, as the RBF theory predicts for distinct points.
- Step 6:Eigenvalues from the engine's Hermitian eigensolver; their sum and product reproduce the trace and the determinant.
The code below puts the whole lesson together on the XOR points with . The squared distances are between neighbours and between opposite corners, so has on the diagonal, for neighbours and for opposite corners. Its eigenvectors are , , and , with eigenvalues , and (twice), all positive. Because is positive definite the dual objective is strictly concave and has a unique maximiser; the symmetries of the square (swapping the two points of a class, or swapping the classes) map maximisers to maximisers, so every equals one number . The dual becomes because is an eigenvector with eigenvalue . The maximiser is , so all four points are free support vectors lying exactly on the margin. The bias from the free support vector is , and SMO reproduces these closed forms.
import { eigvalsh, matrix } from '@/lib/quantum-simulator';
import { svmDecision, trainSvm } from '@/lib/qml';
// RBF kernel k(x, z) = exp(-gamma * ||x - z||^2) and its Gram matrix (rows as Float64Array for trainSvm).
const rbf = (x: number[], z: number[], gamma: number): number =>
Math.exp(-gamma * x.reduce((s, xi, t) => s + (xi - z[t]) ** 2, 0));
const gram = (X: number[][], gamma: number): Float64Array[] =>
X.map((x) => Float64Array.from(X, (z) => rbf(x, z, gamma)));
// XOR: label +1 when both coordinates have the same sign. No line separates these four points.
const X = [[-1, -1], [1, 1], [-1, 1], [1, -1]];
const y = [1, 1, -1, -1];
const gamma = 0.5;
const K = gram(X, gamma);
console.log('K (gamma = 0.5):');
for (const row of K) console.log(Array.from(row, (v) => v.toFixed(6)).join(' '));
// The Gram matrix of a kernel is symmetric positive semidefinite: all eigenvalues are >= 0.
const lam = Array.from(eigvalsh(matrix.fromRows(K.map((r) => Array.from(r))))).sort((a, b) => a - b);
console.log('eigenvalues: ' + lam.map((v) => v.toFixed(10)).join(' '));
const e2 = Math.exp(-2);
const e4 = Math.exp(-4);
console.log('closed form: ' + [1 + e4 - 2 * e2, 1 - e4, 1 - e4, 1 + e4 + 2 * e2].map((v) => v.toFixed(10)).join(' '));
// Soft-margin SVM: the dual QP is solved by SMO on the precomputed Gram matrix.
const model = trainSvm(K, y, { C: 10 });
console.log('alpha = ' + Array.from(model.alpha, (a) => a.toFixed(4)).join(' ') + ', closed form ' + (1 / (1 + e4 - 2 * e2)).toFixed(4));
console.log('support vectors: ' + model.supportIndices.join(' ') + ', |b| < 1e-9: ' + (Math.abs(model.b) < 1e-9));
for (const p of [[0.5, 0.5], [-0.5, 0.5], [0.9, -0.2], [-1.5, -1.2]]) {
const f = svmDecision(model, X.map((x) => rbf(x, p, gamma)));
console.log('f(' + p.join(', ') + ') = ' + f.toFixed(4) + ' -> ' + (f >= 0 ? '+1' : '-1'));
}Expected output
K (gamma = 0.5): 1.000000 0.018316 0.135335 0.135335 0.018316 1.000000 0.135335 0.135335 0.135335 0.135335 1.000000 0.018316 0.135335 0.135335 0.018316 1.000000 eigenvalues: 0.7476450724 0.9816843611 0.9816843611 1.2889862054 closed form: 0.7476450724 0.9816843611 0.9816843611 1.2889862054 alpha = 1.3375 1.3375 1.3375 1.3375, closed form 1.3375 support vectors: 0 1 2 3, |b| < 1e-9: true f(0.5, 0.5) = 0.4162 -> +1 f(-0.5, 0.5) = -0.4162 -> -1 f(0.9, -0.2) = -0.2659 -> -1 f(-1.5, -1.2) = 0.9997 -> +1
Quick check
Which of these symmetric matrices cannot be the Gram matrix of any kernel?
References
- C. Cortes and V. Vapnik, Support-vector networks, Machine Learning 20, 273–297 (1995).doi:10.1007/BF00994018
- B. Schölkopf and A. J. Smola, Learning with Kernels: Support Vector Machines, Regularization, Optimization, and Beyond, MIT Press (2002), chapters 1, 2 and 7.
- J. C. Platt, Sequential Minimal Optimization: A Fast Algorithm for Training Support Vector Machines, Microsoft Research Technical Report MSR-TR-98-14 (1998).microsoft.com
- S. Boyd and L. Vandenberghe, Convex Optimization, Cambridge University Press (2004), §5.1–§5.5 (Lagrange duality, Slater condition, KKT conditions).doi:10.1017/CBO9780511804441
Hands-on labs
The RBF Gram matrix
1 step · auto-gradedOpen labImplement the Gram matrix of the Gaussian (RBF) kernel, the matrix that the SVM dual and every kernel method consume. The grader checks your values on a visible three-point example and on three hidden sets of random points in (), and verifies the two structural properties that every valid Gram matrix has: symmetry and positive semidefiniteness.