Support Vector Machines
The widest street between two classes.
Of the infinitely many lines that separate two classes, the support vector machine picks the one with the widest margin. That single choice turns classification into a convex quadratic program, makes the answer depend only on the training points at or inside the margin, extends to overlapping classes through slack variables, and, through its dual, to curved boundaries with kernels.
What you’ll learn
- Derive the geometric margin of a linear classifier and show that maximizing it is the convex problem subject to , with labels .
- Identify the support vectors and explain why the solution depends on them alone.
- Formulate the soft-margin SVM with slack variables and , and prove it equals -regularized hinge-loss minimization with .
- Write the dual problem, see how kernels enter it, and extend SVMs to several classes.
- Train SVMs well in practice: scaling, choosing and , class weights and probability outputs.
The geometric margin
Throughout, labels are . A linear classifier predicts with ; its decision boundary is the hyperplane . The quantity is positive exactly when the prediction is right, and its size measures confidence, but only up to scale: and define the same classifier. The geometric version removes the scale.
The vector is normal to the hyperplane. Move from along until vanishes:
The step's length is the distance from to the boundary. Signed by the label, it is the geometric margin of the example, positive when it is classified correctly:
Rescale so that the closest points satisfy , the canonical scaling. Then the margin is , and the empty "street" between the hyperplanes and has width .
A trained (canonically scaled) linear SVM has . How wide is its street, the distance between the hyperplanes and ?
Show the answer
0.4
, so the width is and the margin on each side is . A larger means a steeper and a narrower street.
Support vectors
Attach a multiplier to each constraint. The KKT conditions of the quadratic program (proved in Lagrange Duality & KKT Conditions) give two facts that define the method:
So the SVM solution is sparse: delete or move any non-support vector (keeping it outside the street) and the same remains optimal, because all the KKT conditions still hold. This is also the basis of a classic leave-one-out argument: leaving out a non-support vector cannot change the classifier, so leave-one-out errors can only occur at support vectors.
Soft margins and the hinge loss
Real classes overlap, and then no satisfies every constraint. Cortes and Vapnik (1995) relaxed them with slack variables and charged for the slack:
| Slack | Where the point is | Classified |
|---|---|---|
| on or outside its margin hyperplane | correctly | |
| inside the street, on its own side (: on the boundary) | correctly (or on the boundary) | |
| on the wrong side of the boundary | wrongly |
A large makes violations expensive: the street narrows to fit the training points, and as the hard-margin solution returns when the data are separable. A small buys a wide street at the price of many violations, all of which become support vectors. is a regularization parameter, tuned by cross-validation.
For fixed , the best slack is the smallest one allowed by both constraints:
Substituting eliminates the constraints. The term of the margin is the hinge loss:
Divide by : the SVM is empirical risk minimization of the hinge loss with an penalty, the same template as ridge and regularized logistic regression with a different loss.
| Margin | |||||
|---|---|---|---|---|---|
| 0–1 loss | 1 | 1 | 0 | 0 | 0 |
| hinge | 2 | 1 | 0.5 | 0 | 0 |
| squared hinge | 4 | 1 | 0.25 | 0 | 0 |
| logistic | 1.89 | 1 | 0.68 | 0.45 | 0.18 |
A training point ends up with . What are its slack and hinge loss, and is it a support vector?
- : it is correctly classified, so it costs nothing
- , and it is not a support vector
- : it is misclassified
- , hinge loss ; it lies inside the street on its correct side and is a support vector
Show the answer
D. , hinge loss ; it lies inside the street on its correct side and is a support vector
, equal to its hinge loss. Since , the point is correctly classified but inside the margin, and every margin violator is a support vector (with ).
The dual, and where kernels come in
Attach multipliers to the margin constraints and to . Eliminating , and from the Lagrangian leaves a problem in the multipliers alone, the dual:
The Lagrangian of the soft-margin problem, and its stationarity conditions in , and :
Substitute: the terms cancel because , the term vanishes because , and . What remains is a concave quadratic in variables with a box and one equality constraint:
Then . Strong duality, the meaning of each case , and , and the SMO algorithm that solves the dual are in The SVM Dual & Support Vectors.
Look at where the data appear: only in inner products during training and at prediction time. Replace every inner product with a kernel , and the same algorithm finds the maximum-margin hyperplane in the feature space of , which may be enormous or infinite-dimensional, without ever computing :
With the RBF kernel , a prediction is a weighted vote of the support vectors, each fading with distance from . Which functions are valid kernels, and how to choose , is the subject of The Kernel Trick.
| Aspect | Primal | Dual |
|---|---|---|
| Variables | , (plus slacks) | |
| Data enter through | the features | inner products, so kernels fit in |
| Natural when | , linear models (millions of examples, sparse features) | kernels, or |
| Typical solvers | stochastic subgradient (Pegasos), Newton-type methods | SMO and its descendants (LIBSVM) for kernels; dual coordinate descent (LIBLINEAR) for linear SVMs |
SVMs in practice
Scale the features. The margin is measured in Euclidean norm and the RBF kernel uses Euclidean distances, so a feature with a large numeric range dominates. Standardize (or rescale to a fixed range) using training statistics only.
Tune and together, by cross-validation over logarithmic grids such as powers of 10 or of 2. They interact: a large makes each support vector's influence local, and a large lets the fit chase individual points.
Several classes. One-vs-rest trains binary SVMs, class against all others, and predicts . One-vs-one trains pairwise SVMs and lets them vote; LIBSVM uses it, and each pairwise problem is small. There are also single-machine formulations that couple the score functions in one optimization problem (Crammer & Singer, 2001).
Imbalanced classes. Use different penalties and for the two classes (class weights), so violations on the rare class cost more.
Probabilities. An SVM score is not a probability, and its magnitude is not calibrated. If probabilities are needed, fit a sigmoid to held-out scores, which is Platt scaling; Soft Margins & Surrogate Losses explains why the hinge loss cannot do it alone.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC, LinearSVC
from sklearn.model_selection import GridSearchCV
rbf = make_pipeline(StandardScaler(), SVC(kernel='rbf'))
grid = {'svc__C': [0.1, 1, 10, 100], 'svc__gamma': [0.001, 0.01, 0.1, 1]}
search = GridSearchCV(rbf, grid, cv=5).fit(X_train, y_train)
print(search.best_params_, search.score(X_test, y_test))
n_sv = search.best_estimator_[-1].n_support_ # support vectors per class
# Many examples or sparse features: a linear SVM scales far better.
linear = make_pipeline(StandardScaler(), LinearSVC(C=1.0)).fit(X_train, y_train)SVC wraps LIBSVM and handles several classes one-vs-one; LinearSVC wraps LIBLINEAR. With SVC(probability=True), scikit-learn fits Platt scaling with an internal cross-validation.
Cost. Kernel SVM training touches a large share of the kernel values, so in practice its cost grows roughly quadratically in or worse, and prediction costs one kernel evaluation per support vector. On noisy problems the number of support vectors grows linearly with : Steinwart (2003) proved that, with a universal kernel such as the RBF, the fraction of support vectors is asymptotically at least about the Bayes error (and conjectured twice that). Linear SVMs avoid all of this and scale to millions of examples with dual coordinate descent (Hsieh et al., 2008), which reaches an -accurate solution in passes, or with stochastic subgradient methods.
Key takeaways
- With labels , the geometric margin is ; under canonical scaling the street has width , so maximizing the margin is the convex program s.t. .
- The solution involves only support vectors: points on the margin or violating it. Points safely outside the street do not affect it.
- The soft margin adds slacks priced by ; eliminating them gives hinge-loss minimization with an penalty, .
- The dual sees the data only through inner products, so a kernel turns the linear SVM into a nonlinear one: .
- In practice: standardize, tune and jointly by cross-validation on log grids, use one-vs-one or one-vs-rest for several classes, class weights for imbalance, and Platt scaling if probabilities are needed.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A canonically scaled linear SVM has . What is the width of its street?
Show the answer
B.
, so the street between and has width , and the margin on each side is .
In a soft-margin SVM, which training points are support vectors ()?
- Only the misclassified points
- Every point inside the street or misclassified, and (typically) the points exactly on the margin: all have
- Only points exactly on the margin
- All training points
Show the answer
B. Every point inside the street or misclassified, and (typically) the points exactly on the margin: all have
Points with have . Every margin violator, inside the street or misclassified, has . Points exactly on the margin usually have ; in degenerate cases one can have .
A soft-margin SVM with is trained on points. Written as , what is ?
Show the answer
C.
Dividing by gives . Large means weak regularization.
You raise from 0.1 to 1000 on noisy, overlapping data. What typically happens?
- The street narrows, fewer points violate the margin, training error falls, and the risk of overfitting grows
- The street widens and more points become support vectors
- Nothing changes, because only affects the dual
- Test accuracy is guaranteed to improve, because training error falls
Show the answer
A. The street narrows, fewer points violate the margin, training error falls, and the risk of overfitting grows
A larger makes slack expensive, so the optimizer shrinks violations at the cost of a larger , a narrower street. That fits the training data more closely, which can help or hurt on new data; cross-validation decides.
Why does an RBF-kernel SVM usually need standardized features?
- Because the solver only accepts values between and
- Because standardization makes the data linearly separable
- It does not: kernels are invariant to the scale of each feature
- Because depends on Euclidean distances, which a feature with a large numeric range dominates
Show the answer
D. Because depends on Euclidean distances, which a feature with a large numeric range dominates
Both the margin and the RBF kernel measure Euclidean geometry. If one feature is in the thousands and another in the units, the kernel effectively ignores the second. Standardizing puts features on an equal footing, and the same transformation must be applied to new points.
Go deeper
- The SVM Dual & Support Vectors · KKT conditions, sparsity of the solution and SMO.
- Soft Margins & Surrogate Losses · Slack variables, the hinge loss and classification calibration.
- Margin-Based Generalization · Why large margins generalize, whatever the dimension.
Further reading
- C. Cortes & V. Vapnik, "Support-vector networks," Machine Learning 20(3), 273–297 (1995).
- B. E. Boser, I. M. Guyon & V. N. Vapnik, "A training algorithm for optimal margin classifiers," Proceedings of the Fifth Annual Workshop on Computational Learning Theory (COLT), 144–152 (1992).
- B. Schölkopf & A. J. Smola, Learning with Kernels (MIT Press, 2002), chapters 7 and 10.
- C.-C. Chang & C.-J. Lin, "LIBSVM: a library for support vector machines," ACM Transactions on Intelligent Systems and Technology 2(3), article 27 (2011).