Support vector machines and kernels
| Problem | Separate classes by the hyperplane with the widest margin, in a feature space defined implicitly by a kernel; fit regression functions with an ε-insensitive loss |
| Devised by | James Mercer (1909), positive-definite kernels; Vladimir Vapnik and Alexey Chervonenkis (1963–1974), maximal margins and learning theory; Bernhard Boser, Isabelle Guyon and Vapnik (1992), the kernel trick; Corinna Cortes and Vapnik (1995), soft margins; Harris Drucker et al. (1997), support vector regression; John Platt (1998), sequential minimal optimisation; Rong-En Fan, Pai-Hsuen Chen and Chih-Jen Lin (2005), second-order working sets |
| Accuracy | SMO stops when the maximal KKT violation is below (LIBSVM’s default) |
| Cost | Training between and kernel evaluations; prediction per point |
| Read first | Logistic regression, Constrained optimisation: SQP and the augmented Lagrangian method |
| API | SupportVectorMachine (new(kernel, c), decision_function, support_vector_count), SupportVectorRegression (new(kernel, c, epsilon)), Kernel (Linear, Polynomial, Rbf, Sigmoid, gram, rbf_scaled) |
Overview
Among all hyperplanes that separate two classes, the support vector machine (SVM) picks the one farthest from the nearest points, the maximal margin. The solution depends only on those nearest points, the support vectors. Allowing some points inside the margin at a price (the soft margin) handles overlapping classes. And because the optimisation only involves dot products between points, replacing them by a kernel fits a linear separator in a high- or infinite-dimensional feature space without ever computing it, giving curved boundaries in the original space. Before deep learning, kernel SVMs were the most accurate general-purpose classifiers, and they remain strong on small and medium data sets.
Where it is used
Support vector machines find the widest margin between classes and, with kernels, curved boundaries.
- Bioinformatics and chemistry. Classifying proteins, gene-expression profiles and molecules, where there are few samples and many features.
- Image and text classification. Before deep learning, SVMs on hand-designed features were the state of the art for handwriting and face detection.
- Engineering. Fault detection and quality control with small labelled data sets.
- Outlier detection. One-class SVMs describe the region occupied by normal data.
History
James Mercer (1909) characterised the kernels that are inner products in some feature space, and Nachman Aronszajn (1950) developed the theory of reproducing kernel Hilbert spaces. Vladimir Vapnik and Alexey Chervonenkis, in Moscow from 1963, studied optimal separating hyperplanes and founded statistical learning theory. Bernhard Boser, Isabelle Guyon and Vapnik (1992) at Bell Labs combined maximal margins with kernels, and Corinna Cortes and Vapnik (1995) added the soft margin. Harris Drucker, Christopher Burges, Linda Kaufman, Alex Smola and Vapnik (1997) adapted the method to regression. John Platt’s sequential minimal optimisation (1998) made training practical; Rong-En Fan, Pai-Hsuen Chen and Chih-Jen Lin (2005) improved its working-set selection in LIBSVM, the most widely used implementation.
The idea
The maximal-margin hyperplane
The margin. Take two classes with labels and , and a linear classifier that predicts the sign of . The boundary is a hyperplane (a line in two dimensions). If the classes can be separated at all, many hyperplanes separate them. The support vector machine chooses the one that is as far as possible from the nearest training points, on the reasoning that a boundary with room to spare on both sides is least likely to misclassify new points.
To make this precise, note that the distance of a point from the hyperplane is . Multiplying and by a constant does not move the hyperplane, so we may fix the scale by requiring that the closest points have . Every training point then satisfies , the closest points lie on the two parallel hyperplanes , and the gap between those, the margin, has width . Maximising the margin is therefore the same as minimising .
The soft margin. Real classes overlap, and no hyperplane separates them. The soft-margin SVM allows points to violate the margin, at a price:
The slack measures how far point intrudes into the margin: zero if it is on the correct side with room to spare, between 0 and 1 if it is inside the margin but correctly classified, and more than 1 if it is on the wrong side. The parameter sets the price of violations. Small gives a wide margin with many violations; large gives a narrow margin that fits the training data closely.
At the optimum each slack is as small as its constraint allows, . This function of the classifier’s output is called the hinge loss, and substituting it shows that the SVM minimises the total hinge loss plus an penalty on the weights, with strength . In that form it resembles penalised logistic regression, with a different loss. The difference matters: the hinge loss is exactly zero for points beyond the margin, so those points have no influence on the solution at all.
Figure 11.9. Linear SVM with margins.
Only the six points on or inside the margins (highlighted) determine the boundary; the others could move freely without changing it. These are the support vectors.
The dual problem and kernels
The dual. The problem above is a quadratic program with linear constraints, and Lagrange duality transforms it into an equivalent problem in the Lagrange multipliers , one for each training point’s constraint:
The solution of the original problem is recovered as , so the classifier is
Two features of the dual are important. First, by the complementarity condition, a multiplier is nonzero only if its constraint is active: for every point outside the margin. Only the support vectors have , so the sum for has few terms. Second, the training points appear, in both the problem and the classifier, only through dot products .
The kernel trick. A linear boundary is often not enough. One remedy is to compute new features from the old, for instance all products of pairs of features, and fit a linear classifier in the larger feature space; a hyperplane there is a curved surface in the original space. The feature space may be huge. But since the SVM needs only dot products, it never needs the new features themselves, only a function
called a kernel, and for many useful feature maps the kernel can be computed directly from and at trivial cost. In two dimensions, for example, is the dot product of the feature vectors : one multiplication and a square replace the explicit computation of three quadratic features. Replacing every dot product by gives the kernel SVM, with . Any function that is a positive-definite kernel corresponds to a dot product in some feature space and can be used:
- Linear : the original machine.
- Polynomial : the feature space of all monomials up to degree .
- Radial basis function (RBF) : a feature space of infinite dimension. The classifier becomes a sum of Gaussian bumps centred on the support vectors.
- Sigmoid : not positive definite for all parameters.
The kernel width
The RBF parameter sets the reach of each support vector, :
A small gives a smooth, nearly linear boundary; follows the moons; draws an island around nearly every point and makes almost all of them support vectors. and interact and must be chosen together, usually by cross-validation over a grid:
Table 11.7. SVM test accuracy over a grid of and .
| γ = 0.1 | γ = 1 | γ = 10 | γ = 100 | |
|---|---|---|---|---|
| C = 0.1 | 0.815 (151) | 0.895 (117) | 0.933 (182) | 0.834 (200) |
| C = 1 | 0.845 (87) | 0.925 (55) | 0.932 (80) | 0.880 (181) |
| C = 10 | 0.864 (66) | 0.936 (33) | 0.923 (64) | 0.872 (180) |
| C = 100 | 0.906 (51) | 0.924 (26) | 0.887 (53) | 0.872 (180) |
Test accuracy on the moons (200 training points, 2000 test points), with the number of support vectors in brackets.
Sequential minimal optimisation
The dual is a quadratic program with variables, one per training point. Each variable is confined to the interval (a “box”), and there is one equality constraint. A general-purpose solver would need the matrix of kernel values, which is too large for big data sets. Sequential minimal optimisation (SMO) exploits the simple structure of the constraints.
It would be natural to optimise one multiplier at a time, as in coordinate descent, but the constraint forbids it: with all the others fixed, a single multiplier cannot move. The smallest set that can move is two. With two multipliers free, the equality constraint confines them to a line segment inside the box, and the objective along that segment is a quadratic in one variable. Its minimum is given by a formula, clipped to the ends of the segment. SMO repeats this two-variable step until the optimality conditions hold.
The choice of the pair decides the speed. Following LIBSVM, the library chooses the first variable as the one that most violates the optimality conditions, and the second to maximise the guaranteed decrease of the objective (second-order selection). It keeps the gradient of the objective up to date at a cost of per step, and stops when the largest violation falls below the tolerance.
More than two classes are handled one versus one: a separate machine is trained for each pair of classes, and a point is assigned to the class that wins the most pairwise contests.
Support vector regression
ε-insensitive regression ignores errors smaller than and penalises larger ones linearly, : the fit lies inside a tube of half-width where possible, and only points on or outside the tube are support vectors. The library solves the dual subject to by coordinate descent, each coordinate having a closed-form soft-threshold-and-clip update. Adding 1 to the kernel folds the intercept into the kernel (penalising it slightly) and removes the equality constraint.
Figure 11.10. Support vector regression.
Algorithm
Sequential minimal optimisation for two classes. Write the dual objective as with , and let be its gradient.
- Initialise , so that .
- Select the first variable. Let be the indices whose can still move in the direction that increases , and those that can move the other way. Choose in maximising : the variable that most violates the optimality conditions.
- Select the second variable. Among in with , choose minimising , where . That quantity is the decrease in the objective that the pair would achieve, so this picks the most profitable partner.
- Test. The gap between the largest value of over and the smallest over measures how far the solution is from optimal. If it is below the tolerance , stop.
- Update the pair. Move and to the minimum of the objective along the line allowed by the equality constraint, and clip the result so that both stay in .
- Update the gradient for the change in the two multipliers, which needs columns and of the kernel matrix: operations. Go to 2.
When the loop ends, the bias is the average of over the free support vectors (those with ), which lie exactly on the margin.
Prediction: evaluate over the support vectors only, and return its sign.
More than two classes: train one machine for every pair of classes, on the points of those two classes; to predict, let every machine vote and return the class with the most votes.
Implementation
for _ in 0..self.max_iterations {
// Select i: the maximal violator in I_up of -y G.
let mut gmax = f64::NEG_INFINITY;
let mut i = None;
for t in 0..l {
if in_up(t, &alpha) && -y[t] * grad[t] > gmax {
gmax = -y[t] * grad[t];
i = Some(t);
}
}
let Some(i) = i else { break };
// Select j by the second-order rule among I_low violators.
let (mut gmin_obj, mut j, mut gmax2) = (f64::INFINITY, None, f64::NEG_INFINITY);
for t in 0..l {
if in_low(t, &alpha) {
let g = y[t] * grad[t];
gmax2 = gmax2.max(g);
let b = gmax + g;
if b > 0.0 {
let a = (k[[i, i]] + k[[t, t]] - 2.0 * k[[i, t]]).max(1e-12);
let obj = -(b * b) / a;
if obj < gmin_obj {
gmin_obj = obj;
j = Some(t);
}
}
}
}
let Some(j) = j else { break };
if gmax + gmax2 < eps {
break;
}
// Update α_i, α_j keeping yᵀα constant and 0 <= α <= C.
let (old_i, old_j) = (alpha[i], alpha[j]);
let quad = (k[[i, i]] + k[[j, j]] - 2.0 * k[[i, j]]).max(1e-12);
if y[i] != y[j] {
let delta = (-grad[i] - grad[j]) / quad;
let diff = alpha[i] - alpha[j];
alpha[i] += delta;
alpha[j] += delta;
if diff > 0.0 {
if alpha[j] < 0.0 { alpha[j] = 0.0; alpha[i] = diff; }
} else if alpha[i] < 0.0 { alpha[i] = 0.0; alpha[j] = -diff; }
if diff > 0.0 {
if alpha[i] > c { alpha[i] = c; alpha[j] = c - diff; }
} else if alpha[j] > c { alpha[j] = c; alpha[i] = c + diff; }
} else {
let delta = (grad[i] - grad[j]) / quad;
let sum = alpha[i] + alpha[j];
alpha[i] -= delta;
alpha[j] += delta;
if sum > c {
if alpha[i] > c { alpha[i] = c; alpha[j] = sum - c; }
} else if alpha[j] < 0.0 { alpha[j] = 0.0; alpha[i] = sum; }
if sum > c {
if alpha[j] > c { alpha[j] = c; alpha[i] = sum - c; }
} else if alpha[i] < 0.0 { alpha[i] = 0.0; alpha[j] = sum; }
}
let (di, dj) = (alpha[i] - old_i, alpha[j] - old_j);
for t in 0..l {
grad[t] += q(t, i) * di + q(t, j) * dj;
}
}
for _ in 0..self.max_iterations {
let mut max_change: f64 = 0.0;
for i in 0..n {
let kii = k[[i, i]];
let z = y[i] - f[i] + kii * beta[i];
let shrunk = if z > self.epsilon { z - self.epsilon } else if z < -self.epsilon { z + self.epsilon } else { 0.0 };
let new = (shrunk / kii).clamp(-self.c, self.c);
let delta = new - beta[i];
if delta != 0.0 {
for j in 0..n {
f[j] += k[[i, j]] * delta;
}
beta[i] = new;
max_change = max_change.max(delta.abs());
}
}
if max_change < self.tolerance {
break;
}
}
- The full kernel matrix is computed for each binary problem, memory: practical up to a few thousand points.
Kernel::rbf_scaledsets , scikit-learn’s"scale"heuristic.decision_function(two classes only) is positive for class 1.
In practice
//! Kernel support vector machines for classification and regression.
use lib_jsl_core::R2D;
use lib_jsl_machine_learning::common::{Classifier, Regressor, Transformer};
use lib_jsl_machine_learning::datasets::{make_circles, make_sine};
use lib_jsl_machine_learning::kernels::Kernel;
use lib_jsl_machine_learning::metrics::{accuracy, r2_score};
use lib_jsl_machine_learning::preprocessing::StandardScaler;
use lib_jsl_machine_learning::supervised::classification::SupportVectorMachine;
use lib_jsl_machine_learning::supervised::regression::SupportVectorRegression;
fn main() {
// Concentric circles: no line separates them, but an RBF kernel does.
let (x, labels) = make_circles(100, 0.1, 0.5, 1);
let (x_test, test_labels) = make_circles(500, 0.1, 0.5, 2);
for (name, kernel) in [("linear", Kernel::Linear), ("polynomial, degree 2", Kernel::Polynomial { degree: 2, gamma: 1.0, coef0: 1.0 }), ("RBF, γ = 2", Kernel::Rbf { gamma: 2.0 })] {
let mut svm = SupportVectorMachine::new(kernel, 1.0);
svm.fit(x.view(), &labels).unwrap();
println!("{name:<22} accuracy {:.3} with {} support vectors", accuracy(&test_labels, &svm.predict(x_test.view()).unwrap()).unwrap(), svm.support_vector_count());
}
// Regression: standardise x, then fit an ε-tube of width 0.1.
let (x, y) = make_sine(150, 0.1, 3);
let mut scaler = StandardScaler::new();
let xs: R2D = scaler.fit_transform(x.view()).unwrap();
let mut svr = SupportVectorRegression::new(Kernel::Rbf { gamma: 1.0 }, 10.0, 0.1).with_limits(20_000, 1e-8);
svr.fit(xs.view(), y.view()).unwrap();
println!("SVR: R² {:.3} with {} of 150 points as support vectors", r2_score(y.view(), svr.predict(xs.view()).unwrap().view()).unwrap(), svr.support_vector_count());
}
linear accuracy 0.537 with 200 support vectors
polynomial, degree 2 accuracy 0.997 with 49 support vectors
RBF, γ = 2 accuracy 0.995 with 43 support vectors
SVR: R² 0.983 with 50 of 150 points as support vectors
No line separates concentric circles; a degree-2 polynomial kernel, whose feature space contains , separates them almost perfectly.
Strengths
- Flexible nonlinear boundaries through kernels, with a convex training problem and a sparse solution.
- Effective in high dimensions and on small data sets.
Weaknesses
- memory and up to time: unsuitable for very large data sets.
- No probabilities; and the kernel parameters need tuning; features must be scaled.
Exercises
- Show that the margin of the canonical hyperplane is .
- Derive the dual of the soft-margin problem with Lagrange multipliers, and show that for points strictly inside the margin.
- Show that is the inner product of explicit feature vectors in for .
- Show that the RBF kernel matrix is positive definite for distinct points.
- Derive the two-variable SMO update for and its clipping bounds.
Hints and answers
- The hyperplanes are the margin boundaries; the distance between them is .
- The Lagrangian gives , and . Complementarity then implies for points with margin violation (strictly inside the margin or misclassified).
- with .
- Bochner’s theorem: the Gaussian kernel is the Fourier transform of a positive measure with full support, so for distinct points unless all .
- Fix all multipliers but . The constraint keeps constant when ; optimise the resulting quadratic in one variable, and clip to , .
Further reading
- C. Cortes and V. Vapnik, “Support-vector networks”, Machine Learning 20 (1995) 273–297.
- J. C. Platt, “Sequential minimal optimization: a fast algorithm for training support vector machines”, Microsoft Research technical report MSR-TR-98-14, 1998.
- R.-E. Fan, P.-H. Chen and C.-J. Lin, “Working set selection using second order information for training support vector machines”, Journal of Machine Learning Research 6 (2005) 1889–1918.
- C.-C. Chang and C.-J. Lin, “LIBSVM: a library for support vector machines”, ACM Transactions on Intelligent Systems and Technology 2 (2011) 27:1–27:27.
- B. Schölkopf and A. J. Smola, Learning with Kernels, MIT Press, 2002.