Support Vector Machines
- Developed by Vapnik and Cortes in 1995 as a principled margin-maximization classifier
- The kernel trick enabled non-linear classification without explicit high-dimensional feature maps
- Dominated NLP and computer vision before deep learning (2000s)
An SVM finds the hyperplane that maximally separates two classes - the 'widest street' between them. Only the points closest to the boundary (support vectors) determine the decision surface. Kernels allow non-linear boundaries by implicitly mapping data to higher dimensions.
- Generalizes the perceptron by adding the max-margin criterion
- Kernel methods connect to Gaussian processes and kernel PCA
- The dual problem and KKT conditions connect to constrained optimization theory
- Derive the maximum-margin primal and its hard-margin and soft-margin variants.
- Take the Lagrangian, apply the KKT conditions, and obtain the dual quadratic program.
- Explain the kernel trick: only inner products appear in the dual, so $K(x_i, x_j)$ replaces $x_i^\top x_j$.
- State Mercer's condition and the representer theorem, and recognize why the optimal $w$ lies in the span of the training inputs.
- Compare SVMs to perceptron, logistic regression, and kernel ridge regression on loss, output, calibration, and training cost.
TL;DR
A support vector machine (SVM) finds the hyperplane that maximizes the margin between two classes [1]. The primal is a convex quadratic program, and its Lagrangian dual depends on the data only through inner products . Replacing those inner products with a positive semi-definite kernel implicitly maps to a (possibly infinite-dimensional) feature space at no extra cost - the kernel trick [2][3]. The representer theorem says the optimal classifier lies in the span of the training inputs, so the model is a weighted sum over support vectors. Soft-margin SVMs add slack variables and a regularization knob that trades margin width for slack [2]. The standard fitting algorithm is Sequential Minimal Optimization (SMO), which decomposes the dual into analytically solvable two-variable subproblems [4]. SVMs dominated supervised learning roughly 1995-2010 and remain the right tool for small-to-medium tabular datasets with a clear margin.
Intuition
Two linearly separable clouds of points admit infinitely many separating hyperplanes. The SVM picks the one that sits as far as possible from the closest points of either class. The width of the slab between the boundary and those closest points is the margin, and the points that touch the slab edges are the support vectors. Once you have them, the rest of the training set is irrelevant to the model.
Two facts make this work in practice:
- Convex QP. The “max-margin” goal becomes a convex quadratic program with linear constraints, so it has a unique global optimum and well-conditioned solvers [7].
- Kernel trick. The dual depends on the data only through . Replace those with for any positive semi-definite kernel and you get a non-linear classifier without ever computing [3].
VC-style generalization bounds for linear classifiers shrink as the margin grows: a fatter slab means a smaller effective hypothesis class and tighter test-error guarantees, independent of input dimension [2]. The geometric intuition is identical: a wider gap leaves more room for test-time noise before a point crosses the boundary. The hinge loss that falls out of the dual is exactly the convex surrogate that targets this margin.
Figure 1. The SVM picks the hyperplane that maximizes the slab width between the two classes. Only the support vectors (highlighted) constrain the solution; the others can move freely without changing or .
Math
Hard-margin primal: max-margin as a convex QP
Setup
Let with and be linearly separable. A separating hyperplane classifies by .
Functional and geometric margin
For a fixed , the functional margin of example is , and the geometric margin is - the signed Euclidean distance from to the hyperplane.
The geometric margin is invariant to rescaling for , while the functional margin is not. We can therefore fix the scale by requiring the functional margin of the closest point to equal :
Under this normalization, the geometric margin is and the slab width (the gap between the two parallel lines ) is .
The hard-margin primal
Maximizing the slab width is equivalent to minimizing , or equivalently (which is smooth and convex):
This is a convex quadratic program: convex quadratic objective, linear inequality constraints, so it has a unique global minimum if the data is separable [1][7].
Lagrangian, KKT conditions, and the dual
Lagrangian
Introduce dual variables for each constraint and form
Stationarity (primal optimality)
Setting and :
The first equation already encodes the representer theorem for the linearly separable SVM: the optimal is a linear combination of the training inputs, with coefficients .
KKT conditions
For convex QPs with affine constraints, the KKT conditions are necessary and sufficient:
- Primal feasibility: for all .
- Dual feasibility: for all .
- Stationarity: and .
- Complementary slackness: for all .
Complementary slackness has a sharp consequence: forces , meaning lies exactly on the margin. Those are the support vectors. Every other example has and therefore contributes nothing to .
The dual
Substituting back into and simplifying yields the dual problem - a quadratic in alone:
Three things are crucial about this form [7][6]:
- The dual is again a convex QP (the matrix with entries is positive semi-definite).
- Strong duality holds (Slater’s condition), so the dual optimum equals the primal optimum.
- The data appears only through the inner products . This is what enables the kernel trick.
Recovering the bias
Pick any support vector (with ). Complementary slackness gives , so
In practice we average this over all support vectors for numerical stability.
Soft-margin SVM: slack variables and the role of $C$
Real data is rarely linearly separable. The soft-margin SVM [2] introduces non-negative slack variables that allow individual examples to violate the margin:
Examples with are correctly classified outside the margin; with they sit inside the margin but on the correct side; with they are misclassified. The parameter is a regularization knob trading margin width for slack: large heavily penalizes slack and produces a narrow, low-bias / high-variance margin; small tolerates slack and produces a wide, high-bias / low-variance margin.
Soft-margin dual
A near-identical derivation yields the dual
The single change from the hard-margin dual is the box constraint on each dual variable. KKT now classifies points into three groups:
- : outside the margin, no influence.
- : exactly on the margin (a margin support vector); .
- : inside the margin or misclassified; takes up the slack.
Equivalent hinge-loss form
Eliminating the slacks by choosing rewrites the soft-margin problem as
That second sum is the hinge loss . The hinge loss is convex but non-smooth at , which is why direct primal optimization needs subgradient methods or the dual form [6].
The kernel trick
In the dual, the data appears only through inner products . If we instead apply some feature map to a (possibly very high-dimensional) Hilbert space and replace with , the entire derivation goes through unchanged. Define a kernel function
and the dual becomes
The classifier at test time is
so we never need explicitly - only the kernel [3].
The standard kernel zoo
| Kernel | K(x, y) | Implicit feature space | When to use |
|---|---|---|---|
| Linear | x^T y | R^d itself | High-dimensional sparse data (text TF-IDF), as a baseline. |
| Polynomial (degree d, offset c) | (x^T y + c)^d | monomials of degree at most d in the original features | When you suspect feature interactions of bounded degree. |
| Gaussian / RBF | exp(-gamma * ||x - y||^2) | infinite-dimensional Hilbert space (Gaussian basis) | Generic non-linear default; gamma controls smoothness. |
| Sigmoid (tanh) | tanh(kappa * x^T y + c) | not always PSD; matches a 1-hidden-layer NN | Historical interest; not always Mercer-valid. |
Mercer's condition: which functions are valid kernels?
A function is a valid kernel (i.e. corresponds to an inner product in some Hilbert space) if and only if for every finite set the Gram matrix
is symmetric and positive semi-definite (PSD): for every .
This is Mercer’s condition (after Mercer’s 1909 theorem on continuous kernels on a compact domain) [3]. It is the bridge between the algebraic (“the dual is PSD”) and analytic (“there exists a feature map ”) views of kernels.
Why we care
Mercer’s condition guarantees:
- The dual SVM problem is convex, so a unique global optimum exists.
- There is some feature map with , even if we never construct it.
- Closure properties: sums, products, and positive scalar multiples of valid kernels are valid kernels, so we can compose new ones.
The sigmoid kernel fails Mercer for many parameter values, which is why it sometimes “works” empirically and sometimes makes solvers blow up - the dual stops being convex when has negative eigenvalues.
Representer theorem: the optimal classifier lives in the span of training inputs
Statement (Schölkopf-Smola form)
Let be a reproducing-kernel Hilbert space (RKHS) with kernel and norm . Consider a regularized learning problem of the form
where is any pointwise loss and is a strictly increasing function. Then any minimizer admits a representation
for some coefficients [3].
Proof sketch
Decompose the RKHS as , where is the finite-dimensional subspace spanned by the training-input feature maps and is its orthogonal complement.
Any splits as with and . By the reproducing property , and orthogonality kills at every training input:
So the loss term depends only on . The regularizer is strictly increasing and Pythagoras gives , so adding any non-zero strictly increases the regularizer without changing the loss. Therefore the minimizer must have , i.e. . ∎
What it buys
The representer theorem reduces an infinite-dimensional optimization (over all of ) to a finite-dimensional one (over the coefficients ). It is the reason all kernel methods - SVMs, kernel ridge regression, kernel PCA, Gaussian processes - reduce to algebra in rather than functional analysis. The SVM specifically chooses the via the dual, which makes most of them zero (sparse expansion in support vectors).
SMO: how the dual is actually solved
The dual is a convex QP in variables with box constraints and one equality constraint. Generic QP solvers scale poorly when is in the tens of thousands, and constructing the full kernel matrix is memory. Sequential Minimal Optimization (SMO) decomposes the dual into the smallest possible subproblems and solves them analytically [4].
The key idea: pick a pair to update, fix all the others, and solve the resulting two-variable QP in closed form. Two variables are necessary (not just one) because the equality constraint couples them.
| Step | Operation |
|---|---|
| 1 | Choose two Lagrange multipliers (alpha_i, alpha_j) violating the KKT conditions most strongly (heuristic working-set selection). |
| 2 | Hold all other alphas fixed. The equality constraint forces alpha_i + s * alpha_j = const, where s = y_i * y_j. |
| 3 | Solve the resulting one-dimensional QP in alpha_j analytically; clip to the box [0, C] using the linear constraint. |
| 4 | Recompute the bias b from any margin support vector. |
| 5 | Repeat until KKT conditions are satisfied to a tolerance. |
SMO never needs the full kernel matrix at once - it computes kernel rows on
demand - and its per-iteration cost is constant. The total cost is empirically
to for many problems, far better than naive QP solvers.
Modern libraries (LIBSVM, sklearn’s SVC) use SMO under the hood with
working-set-selection heuristics that improve on Platt’s original choice.
Why SVMs were dominant 1995-2010
Before the ImageNet moment, SVMs were the default supervised classifier across academia and industry. Three reasons:
- Strong theory. VC bounds, the kernel trick, and convex duality gave a clean explanation of why the model works, not just that it works [2].
- Empirical performance. With an RBF kernel and a tuned , SVMs outperformed neural nets on most small-to-medium tabular and text benchmarks until backpropagation was rescued by GPUs and large datasets.
- No hyperparameter zoo. Two knobs (, ) and a kernel choice covered most use cases. Compared with the architecture-and-optimizer search of modern deep learning, this was a gift.
Their fall from dominance is also explained by their structure: the -to- training cost and dense-kernel-matrix memory wall do not scale to millions of examples, which is exactly what deep nets started feeding on in 2012.
How SVMs compare to related linear models
| Model | Loss | Output | Calibrated probabilities? | Kernel support | Training cost |
|---|---|---|---|---|---|
| Perceptron | perceptron loss: max(0, -y * (w^T x + b)) | sign(w^T x + b) | no | kernel perceptron exists, rarely used | O(n) per pass; converges in finite steps if separable. |
| Logistic regression | logistic / cross-entropy: log(1 + exp(-y * (w^T x + b))) | sigma(w^T x + b) | yes (trained on log-likelihood) | kernel logistic regression possible but loses sparsity | O(n d) per IRLS iteration; full data each step. |
| SVM (hinge) | hinge: max(0, 1 - y * (w^T x + b)) | sign(w^T x + b) | no (Platt scaling adds them post hoc) | native via the dual; sparse in support vectors | O(n^2) to O(n^3) typical; SMO scales to n in the tens of thousands. |
| Kernel ridge regression | squared: (y - f(x))^2 + lambda * ||f||_H^2 | real-valued f(x), then threshold | no (regression to real-valued targets) | native; closed form via (K + lambda I)^(-1) y | O(n^3) for the matrix solve; dense in all training points (no sparsity). |
A quick mnemonic: SVM gives you margin + sparsity; logistic regression gives you probabilities; kernel ridge gives you a closed form but no sparsity; the perceptron [8] gives you the cheapest convergence guarantee.
Implementations
Three idiomatic implementations of the soft-margin SVM. The numpy version
sketches the dual as a generic QP fed to scipy.optimize.minimize (purely
illustrative; production solvers use SMO); the sklearn-svc version is the
production default with an RBF kernel; the sklearn-nystroem version
approximates the kernel feature map and feeds a LinearSVC for scale.
import numpy as np
from scipy.optimize import minimize
def fit_svm_dual(X, y, C=1.0):
"""Sketch: solve the soft-margin dual via a generic QP solver.
Production code uses SMO (Platt 1998); this shows the math, not the speed.
y is in {-1, +1}.
"""
n = X.shape[0]
K = X @ X.T # linear kernel
P = (np.outer(y, y)) * K # n x n PSD matrix
q = -np.ones(n)
bounds = [(0, C)] * n # 0 <= alpha_i <= C
def neg_dual(alpha): # minimize -dual
return 0.5 * alpha @ P @ alpha + q @ alpha
def neg_dual_grad(alpha):
return P @ alpha + q
cons = ({'type': 'eq', 'fun': lambda a: a @ y})
res = minimize(neg_dual, np.zeros(n), jac=neg_dual_grad,
bounds=bounds, constraints=cons, method='SLSQP')
alpha = res.x
# Recover w from the representer formula and b from a margin SV.
w = (alpha * y) @ X
sv = (alpha > 1e-5) & (alpha < C - 1e-5) # margin support vectors
b = np.mean(y[sv] - X[sv] @ w) if sv.any() else 0.0
return w, b, alpha
# tiny synthetic example
rng = np.random.default_rng(0)
X = np.vstack([rng.normal(loc=[-2, 0], size=(20, 2)),
rng.normal(loc=[+2, 0], size=(20, 2))])
y = np.array([-1] * 20 + [+1] * 20)
w, b, alpha = fit_svm_dual(X, y, C=1.0)
print("w :", np.round(w, 3))
print("b :", round(float(b), 3))
print("# support vectors:", int((alpha > 1e-5).sum()))Run a small sklearn SVC with an RBF kernel on make_moons live in the
browser to see the non-linear decision boundary that the kernel trick buys:
(no output yet)
Real-world uses
| Domain | System | Why SVMs |
|---|---|---|
| Text classification (1995-2010) | Spam filters, news topic classifiers, sentiment analysis with bag-of-words / TF-IDF features | Linear SVM on sparse high-dimensional features dominated until LR caught up; the dual makes the kernel trick optional but the duality view stays useful. |
| Bioinformatics | Microarray gene-expression classifiers; protein structure prediction | High-d, small-n tabular data; the margin gives sane generalization where logistic regression overfits without strong regularization. |
| Computer vision (pre-deep-learning) | HOG + linear SVM for pedestrian detection (Dalal-Triggs 2005); SIFT + bag-of-visual-words + RBF SVM | The standard pipeline before CNNs ate the field in 2012. |
| Anomaly detection | One-class SVM for novelty detection on tabular telemetry | Kernelized boundary in the feature space; handles non-linear "normal regions" without distributional assumptions. |
| Small tabular Kaggle / business analytics | Default non-tree baseline alongside logistic regression | Strong out-of-the-box accuracy on n in the thousands with low feature dimension. |
Pitfalls
The RBF kernel measures distance in
the raw feature units. A feature in millimetres and a feature in
kilometres have wildly different effective values, and one will
dominate. Wrap the SVC in a StandardScaler (or MinMaxScaler) and treat
that as a non-negotiable. The same applies to polynomial kernels with offset.
SVC(C=1.0) is a placeholder, not a recommendation. The optimal depends
on noise level, class balance, and feature scale. A grid search over
paired with
is the cheapest way to get an honest estimate. Using class_weight='balanced'
helps under heavy class imbalance.
The decision function is a signed distance, not a calibrated
probability. The probability=True flag in sklearn turns on Platt scaling
(fit a logistic regression to the SVM scores on a held-out fold)
[5], which adds a training-time
cost and is still less calibrated than logistic regression itself. If you
need probabilities, prefer logistic regression, or use the SVM only for the
hard label and calibrate post hoc with CalibratedClassifierCV.
LIBSVM-backed solvers are far slower than - in the worst case the
kernel matrix is dense and every QP iteration touches all of it. Beyond a
few hundred thousand examples, prefer Nystroem / RBFSampler + LinearSVC,
or move to gradient boosting / a small neural net. SVMs do not scale
to “modern” dataset sizes the way logistic regression and trees do.
For text bags-of-words and TF-IDF features (millions of features, mostly
zeros), LinearSVC (with squared hinge loss and dual=False) is one of the
fastest, most accurate baselines you can run. Logistic regression with the
same features is essentially tied; pick whichever you prefer for the
calibration story.
Interview Q&A
Derive the hard-margin SVM primal and dual.research
Primal. Given linearly separable with , fix the scale by . The geometric margin is then , so maximizing the slab width is equivalent to
This is a convex QP with linear inequality constraints.
Lagrangian. With multipliers ,
Stationarity. gives , and gives .
Dual. Substituting back,
Strong duality holds (Slater’s condition is automatic for affine constraints with non-empty feasible set), so primal and dual optima coincide. KKT complementary slackness shows that implies lies on the margin: those are the support vectors [1][7].
Sketch the proof of the representer theorem and explain why it matters.research
Setup. Let be an RKHS with kernel , and consider
with strictly increasing.
Decomposition. Let and its orthogonal complement. Any writes uniquely as with , .
Loss term. By the reproducing property , and orthogonality kills at training inputs: . So the loss depends only on .
Regularizer. Pythagoras gives . Since is strictly increasing, any non-zero strictly increases the regularizer without changing the loss. So the minimizer has , i.e. , which means
Why it matters. The theorem reduces an infinite-dimensional optimization problem to an -dimensional one. It is the reason every kernel method - SVMs, kernel ridge, kernel PCA, Gaussian processes - reduces to algebra in [3]. For SVMs specifically, the dual makes most zero, giving the sparse expansion in support vectors.
State the kernel trick formally. Why don't we ever need $\phi(x)$?onsite
The dual SVM objective and the test-time decision function depend on the data only through inner products . Replacing those with for any map to a Hilbert space gives the kernelized version
We never compute directly. Mercer’s condition (PSD Gram matrix on every finite subset) guarantees that some such exists, even though we may not be able to write it down in closed form. For the RBF kernel , lives in an infinite-dimensional space, yet is computable in [3]. The kernel trick decouples expressive feature space from compute cost, and that decoupling is what enabled non-linear SVMs to dominate from 1995 to 2010.
In the soft-margin SVM, why does $C$ trade margin width for slack?onsite
The soft-margin objective
balances two terms:
- rewards small , which means a wide margin (slab width ).
- penalizes margin violations, with larger making each unit of slack more expensive.
Large : slack is very expensive, so the optimizer drives even at the cost of a large - a narrow margin that is intolerant of noise (low bias, high variance). In the limit this is the hard-margin SVM, which only exists for linearly separable data.
Small : slack is cheap, so the optimizer prefers a wide margin even if many points violate it (high bias, low variance). Many examples land at in the dual (bound support vectors).
The dual makes this concrete: the box constraint caps how much any single example can pull on . Smaller caps the influence sooner, which limits overfitting to outliers. In practice, is the regularization knob and is selected by cross-validation [2][6].
State Mercer's theorem. Why is it the right characterization of a valid kernel?research
Statement (finite version). A symmetric function is a valid (Mercer) kernel if and only if for every finite set , the Gram matrix is symmetric and positive semi-definite.
Equivalently (Mercer’s original 1909 statement on a compact domain): if is a continuous symmetric kernel on for compact , and the integral operator is positive semi-definite, then admits an eigen-expansion
with an orthonormal basis of eigenfunctions. Setting gives an explicit feature map satisfying .
Why it is the right condition.
- Existence of . PSD-ness is exactly what is needed for to be the inner product of some feature map in a Hilbert space.
- Convexity of the dual. The dual SVM objective has Hessian , which is PSD if and only if is - so Mercer’s condition is what makes the dual a convex QP with a unique global optimum.
- Closure properties. Sums, products, scalar multiples (by non-negative scalars), and tensor products of valid kernels are valid kernels, so Mercer’s condition is preserved by all the natural ways to compose kernels [3].
The sigmoid kernel is the textbook example of a “kernel” that fails Mercer for many parameter values, which is why it sometimes gives non-convex training and unreliable test-time behaviour.
- 1. In the hard-margin SVM dual, what is the role of the constraint sum_i alpha_i * y_i = 0?
- 2. What does the representer theorem say about the optimal classifier in an RKHS?
- 3. Which of the following is NOT a valid Mercer kernel for all parameter settings?
- 4. In the soft-margin dual, what does alpha_i = C imply about example i?
- 5. Why do SVMs not output calibrated probabilities natively?
A short evening project to internalize SVMs:
- Implement the soft-margin dual on a 2-D synthetic dataset using
scipy.optimize.minimizewith SLSQP, exactly as in the numpyCodeCompareblock above. Plot the decision boundary, the two margin lines, and circle the support vectors. - Swap the linear kernel for an RBF kernel by replacing with the Gaussian Gram matrix. Confirm the boundary curves around
make_moons. - Implement a tiny SMO loop: pick the two most KKT-violating , solve the analytic 2-var QP, clip to the box, and repeat. Compare iterations to the SLSQP path on the same problem.
- Stretch: add Platt scaling on top of the SVM scores using a held-out fold, and compare the resulting calibration to logistic regression with the same features (use a reliability diagram).
Interactive Demo
References
- Boser, B. E., Guyon, I. M., and Vapnik, V. N. (1992). A training algorithm for optimal margin classifiers. Proceedings of the Fifth Annual Workshop on Computational Learning Theory (COLT) 144-152. doi:10.1145/130385.130401
- Cortes, C. and Vapnik, V. (1995). Support-vector networks. Machine Learning 20(3), 273-297. doi:10.1007/BF00994018
- Schölkopf, B. and Smola, A. J. (2002). Learning with Kernels: Support Vector Machines, Regularization, Optimization, and Beyond. MIT Press. ISBN 978-0-262-19475-4
- Platt, J. C. (1998). Sequential Minimal Optimization: A Fast Algorithm for Training Support Vector Machines. Microsoft Research Technical Report MSR-TR-98-14. https://www.microsoft.com/en-us/research/publication/sequential-minimal-optimization-a-fast-algorithm-for-training-support-vector-machines/
- Platt, J. C. (1999). Probabilistic outputs for support vector machines and comparisons to regularized likelihood methods. Advances in Large Margin Classifiers, MIT Press, 61-74. ISBN 978-0-262-19448-8
- Hastie, T., Tibshirani, R., and Friedman, J. (2009). The Elements of Statistical Learning, 2nd ed.. Springer. https://hastie.su.domains/ElemStatLearn/
- Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer. ISBN 978-0-387-31073-2
- Rosenblatt, F. (1958). The Perceptron: A Probabilistic Model for Information Storage and Organization in the Brain. Psychological Review 65(6), 386-408. doi:10.1037/h0042519