Simple Algorithm
Machine Learning · Descent · 24 min

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 min⁡12∥w∥2\min \tfrac12\norm{\mathbf w}^2 subject to yi(w⊤xi+b)≥1y_i(\mathbf w^\top\mathbf x_i + b) \ge 1, with labels y∈{−1,+1}y \in \{-1, +1\}.
  • Identify the support vectors and explain why the solution depends on them alone.
  • Formulate the soft-margin SVM with slack variables and CC, and prove it equals ℓ2\ell_2-regularized hinge-loss minimization with λ=1/(nC)\lambda = 1/(nC).
  • Write the dual problem, see how kernels enter it, and extend SVMs to several classes.
  • Train SVMs well in practice: scaling, choosing CC and γ\gamma, class weights and probability outputs.

The geometric margin

Throughout, labels are y∈{−1,+1}y \in \{-1, +1\}. A linear classifier predicts sign⁡f(x)\sign f(\mathbf x) with f(x)=w⊤x+bf(\mathbf x) = \mathbf w^\top\mathbf x + b; its decision boundary is the hyperplane f=0f = 0. The quantity yf(x)y f(\mathbf x) is positive exactly when the prediction is right, and its size measures confidence, but only up to scale: (w,b)(\mathbf w, b) and (2w,2b)(2\mathbf w, 2b) define the same classifier. The geometric version removes the scale.

DerivationDistance to the hyperplane
  1. x⊥=x−f(x)∥w∥2 w⟹f(x⊥)=w⊤x+b−f(x)=0\mathbf x_\perp = \mathbf x - \frac{f(\mathbf x)}{\norm{\mathbf w}^2}\,\mathbf w \qquad\Longrightarrow\qquad f(\mathbf x_\perp) = \mathbf w^\top\mathbf x + b - f(\mathbf x) = 0

    The vector w\mathbf w is normal to the hyperplane. Move from x\mathbf x along w\mathbf w until ff vanishes:

  2. γi=yi (w⊤xi+b)∥w∥,γ(w,b)=min⁡iγi\gamma_i = \frac{y_i\,(\mathbf w^\top\mathbf x_i + b)}{\norm{\mathbf w}},\qquad \gamma(\mathbf w, b) = \min_i \gamma_i

    The step's length is the distance from x\mathbf x to the boundary. Signed by the label, it is the geometric margin of the example, positive when it is classified correctly:

  3. min⁡iyif(xi)=1⟹γ=1∥w∥,street width=2∥w∥\min_i y_i f(\mathbf x_i) = 1 \quad\Longrightarrow\quad \gamma = \frac1{\norm{\mathbf w}},\qquad \text{street width} = \frac2{\norm{\mathbf w}}

    Rescale (w,b)(\mathbf w, b) so that the closest points satisfy yif(xi)=1y_i f(\mathbf x_i) = 1, the canonical scaling. Then the margin is 1/∥w∥1/\norm{\mathbf w}, and the empty "street" between the hyperplanes f=−1f = -1 and f=+1f = +1 has width 2/∥w∥2/\norm{\mathbf w}.

Predict before you look

A trained (canonically scaled) linear SVM has w=(3,4)\mathbf w = (3, 4). How wide is its street, the distance between the hyperplanes f=−1f = -1 and f=+1f = +1?

Show the answer

0.4

∥w∥=9+16=5\norm{\mathbf w} = \sqrt{9 + 16} = 5, so the width is 2/5=0.42/5 = 0.4 and the margin on each side is 0.20.2. A larger ∥w∥\norm{\mathbf w} means a steeper ff and a narrower street.

Support vectors

Attach a multiplier αi≥0\alpha_i \ge 0 to each constraint. The KKT conditions of the quadratic program (proved in Lagrange Duality & KKT Conditions) give two facts that define the method:

w⋆=∑i=1nαi yi xi,αi[yi(w⋆⊤xi+b⋆)−1]=0  for every i\mathbf w^\star = \sum_{i=1}^n \alpha_i\,y_i\,\mathbf x_i,\qquad \alpha_i\big[y_i(\mathbf w^{\star\top}\mathbf x_i + b^\star) - 1\big] = 0\ \text{ for every } i
The solution is a combination of training points, and complementary slackness forces αi=0\alpha_i = 0 for every point strictly outside the street. Only points exactly on the margin can carry weight: the support vectors.

So the SVM solution is sparse: delete or move any non-support vector (keeping it outside the street) and the same (w⋆,b⋆)(\mathbf w^\star, b^\star) 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 (w,b)(\mathbf w, b) satisfies every constraint. Cortes and Vapnik (1995) relaxed them with slack variables ξi≥0\xi_i \ge 0 and charged for the slack:

min⁡w,b,ξ 12∥w∥2+C∑i=1nξisubject toyi(w⊤xi+b)≥1−ξi,ξi≥0\min_{\mathbf w, b, \boldsymbol\xi}\ \tfrac12\norm{\mathbf w}^2 + C\sum_{i=1}^n \xi_i \quad\text{subject to}\quad y_i(\mathbf w^\top\mathbf x_i + b) \ge 1 - \xi_i,\quad \xi_i \ge 0
The soft-margin SVM. C>0C > 0 prices margin violations against margin width.
SlackWhere the point isClassified
ξi=0\xi_i = 0on or outside its margin hyperplanecorrectly
0<ξi≤10 < \xi_i \le 1inside the street, on its own side (ξi=1\xi_i = 1: on the boundary)correctly (or on the boundary)
ξi>1\xi_i > 1on the wrong side of the boundarywrongly
Every training error has ξi>1\xi_i > 1, so ∑iξi\sum_i \xi_i is an upper bound on the number of training errors.

A large CC makes violations expensive: the street narrows to fit the training points, and as C→∞C \to \infty the hard-margin solution returns when the data are separable. A small CC buys a wide street at the price of many violations, all of which become support vectors. CC is a regularization parameter, tuned by cross-validation.

DerivationThe soft-margin SVM is regularized hinge-loss minimization
  1. ξi⋆=max⁡(0, 1−yif(xi))=[1−yif(xi)]+\xi_i^\star = \max\big(0,\ 1 - y_i f(\mathbf x_i)\big) = \big[1 - y_i f(\mathbf x_i)\big]_+

    For fixed (w,b)(\mathbf w, b), the best slack is the smallest one allowed by both constraints:

  2. min⁡w,b 12∥w∥2+C∑i=1n[1−yif(xi)]+\min_{\mathbf w, b}\ \tfrac12\norm{\mathbf w}^2 + C\sum_{i=1}^n\big[1 - y_i f(\mathbf x_i)\big]_+

    Substituting eliminates the constraints. The term [1−m]+[1 - m]_+ of the margin m=yf(x)m = yf(\mathbf x) is the hinge loss:

  3. min⁡w,b 1n∑i=1n[1−yif(xi)]++λ2∥w∥2,λ=1nC\min_{\mathbf w, b}\ \frac1n\sum_{i=1}^n\big[1 - y_i f(\mathbf x_i)\big]_+ + \frac\lambda2\norm{\mathbf w}^2,\qquad \lambda = \frac1{nC}

    Divide by nCnC: the SVM is empirical risk minimization of the hinge loss with an ℓ2\ell_2 penalty, the same template as ridge and regularized logistic regression with a different loss.

Margin m=yf(x)m = yf(\mathbf x)−1-1000.50.51122
0–1 loss 1{m≤0}\mathbf 1\{m \le 0\}11000
hinge [1−m]+[1 - m]_+210.500
squared hinge [1−m]+2[1 - m]_+^2410.2500
logistic log⁡2(1+e−m)\log_2(1 + e^{-m})1.8910.680.450.18
All three surrogates upper-bound the 0–1 loss and are convex. The hinge is exactly zero once m≥1m \ge 1, which is what makes SVM solutions sparse; the logistic loss is never zero, so every point keeps some weight.
Check your understanding

A training point ends up with yif(xi)=0.4y_i f(\mathbf x_i) = 0.4. What are its slack and hinge loss, and is it a support vector?

  1. ξi=0\xi_i = 0: it is correctly classified, so it costs nothing
  2. ξi=0.4\xi_i = 0.4, and it is not a support vector
  3. ξi=1.4\xi_i = 1.4: it is misclassified
  4. ξi=0.6\xi_i = 0.6, hinge loss 0.60.6; it lies inside the street on its correct side and is a support vector
Show the answer

D. ξi=0.6\xi_i = 0.6, hinge loss 0.60.6; it lies inside the street on its correct side and is a support vector

ξi=[1−0.4]+=0.6\xi_i = [1 - 0.4]_+ = 0.6, equal to its hinge loss. Since 0<ξi≤10 < \xi_i \le 1, the point is correctly classified but inside the margin, and every margin violator is a support vector (with αi=C\alpha_i = C).

The dual, and where kernels come in

Attach multipliers αi≥0\alpha_i \ge 0 to the margin constraints and μi≥0\mu_i \ge 0 to ξi≥0\xi_i \ge 0. Eliminating w\mathbf w, bb and ξ\boldsymbol\xi from the Lagrangian leaves a problem in the multipliers alone, the dual:

DerivationFrom the Lagrangian to the dual
  1. L=12∥w∥2+C∑iξi−∑iαi[yi(w⊤xi+b)−1+ξi]−∑iμiξiw=∑iαiyixi,∑iαiyi=0,αi=C−μi≤C\begin{aligned} \mathcal L &= \tfrac12\norm{\mathbf w}^2 + C\sum_i\xi_i - \sum_i\alpha_i\big[y_i(\mathbf w^\top\mathbf x_i + b) - 1 + \xi_i\big] - \sum_i\mu_i\xi_i\\ \mathbf w &= \sum_i\alpha_iy_i\mathbf x_i,\qquad \sum_i\alpha_iy_i = 0,\qquad \alpha_i = C - \mu_i \le C \end{aligned}

    The Lagrangian of the soft-margin problem, and its stationarity conditions in w\mathbf w, bb and ξi\xi_i:

  2. max⁡α ∑i=1nαi−12∑i=1n∑j=1nαiαj yiyj xi⊤xjsubject to0≤αi≤C,∑i=1nαiyi=0\max_{\boldsymbol\alpha}\ \sum_{i=1}^n\alpha_i - \frac12\sum_{i=1}^n\sum_{j=1}^n\alpha_i\alpha_j\,y_iy_j\,\mathbf x_i^\top\mathbf x_j \quad\text{subject to}\quad 0 \le \alpha_i \le C,\quad \sum_{i=1}^n\alpha_iy_i = 0

    Substitute: the ξ\xi terms cancel because C−αi−μi=0C - \alpha_i - \mu_i = 0, the bb term vanishes because ∑iαiyi=0\sum_i\alpha_iy_i = 0, and 12∥w∥2−∑iαiyiw⊤xi=−12∥w∥2\tfrac12\norm{\mathbf w}^2 - \sum_i\alpha_iy_i\mathbf w^\top\mathbf x_i = -\tfrac12\norm{\mathbf w}^2. What remains is a concave quadratic in nn variables with a box and one equality constraint:

  3. Then f(x)=∑iαiyi xi⊤x+bf(\mathbf x) = \sum_i\alpha_iy_i\,\mathbf x_i^\top\mathbf x + b. Strong duality, the meaning of each case αi=0\alpha_i = 0, 0<αi<C0 < \alpha_i < C and αi=C\alpha_i = C, 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 xi⊤xj\mathbf x_i^\top\mathbf x_j during training and xi⊤x\mathbf x_i^\top\mathbf x at prediction time. Replace every inner product with a kernel k(xi,xj)=φ(xi)⊤φ(xj)k(\mathbf x_i, \mathbf x_j) = \varphi(\mathbf x_i)^\top\varphi(\mathbf x_j), and the same algorithm finds the maximum-margin hyperplane in the feature space of φ\varphi, which may be enormous or infinite-dimensional, without ever computing φ\varphi:

f(x)=∑i: αi>0αi yi k(xi,x)+b.f(\mathbf x) = \sum_{i:\ \alpha_i > 0}\alpha_i\,y_i\,k(\mathbf x_i, \mathbf x) + b.

With the RBF kernel k(x,z)=e−γ∥x−z∥2k(\mathbf x, \mathbf z) = e^{-\gamma\norm{\mathbf x - \mathbf z}^2}, a prediction is a weighted vote of the support vectors, each fading with distance from x\mathbf x. Which functions are valid kernels, and how to choose γ\gamma, is the subject of The Kernel Trick.

AspectPrimalDual
Variablesw∈Rd\mathbf w \in \R^d, bb (plus slacks)α∈Rn\boldsymbol\alpha \in \R^n
Data enter throughthe features xi\mathbf x_iinner products, so kernels fit in
Natural whend≪nd \ll n, linear models (millions of examples, sparse features)kernels, or d≫nd \gg n
Typical solversstochastic subgradient (Pegasos), Newton-type methodsSMO 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 CC and γ\gamma together, by cross-validation over logarithmic grids such as powers of 10 or of 2. They interact: a large γ\gamma makes each support vector's influence local, and a large CC lets the fit chase individual points.

Several classes. One-vs-rest trains KK binary SVMs, class kk against all others, and predicts arg max⁡kfk(x)\argmax_k f_k(\mathbf x). One-vs-one trains K(K−1)/2K(K-1)/2 pairwise SVMs and lets them vote; LIBSVM uses it, and each pairwise problem is small. There are also single-machine formulations that couple the KK score functions in one optimization problem (Crammer & Singer, 2001).

Imbalanced classes. Use different penalties C+C_+ and C−C_- 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 P(y=1∣f)=1/(1+eAf+B)P(y = 1 \mid f) = 1/(1 + e^{Af + B}) to held-out scores, which is Platt scaling; Soft Margins & Surrogate Losses explains why the hinge loss cannot do it alone.

python
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 n2n^2 kernel values, so in practice its cost grows roughly quadratically in nn or worse, and prediction costs one kernel evaluation per support vector. On noisy problems the number of support vectors grows linearly with nn: 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 ε\varepsilon-accurate solution in O(log⁡(1/ε))\order{\log(1/\varepsilon)} passes, or with stochastic subgradient methods.

Key takeaways

  • With labels y∈{−1,+1}y \in \{-1, +1\}, the geometric margin is yf(x)/∥w∥y f(\mathbf x)/\norm{\mathbf w}; under canonical scaling the street has width 2/∥w∥2/\norm{\mathbf w}, so maximizing the margin is the convex program min⁡12∥w∥2\min\tfrac12\norm{\mathbf w}^2 s.t. yif(xi)≥1y_i f(\mathbf x_i) \ge 1.
  • The solution w⋆=∑iαiyixi\mathbf w^\star = \sum_i \alpha_i y_i\mathbf x_i 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 CC; eliminating them gives hinge-loss minimization with an ℓ2\ell_2 penalty, λ=1/(nC)\lambda = 1/(nC).
  • The dual sees the data only through inner products, so a kernel turns the linear SVM into a nonlinear one: f(x)=∑iαiyik(xi,x)+bf(\mathbf x) = \sum_i\alpha_iy_ik(\mathbf x_i, \mathbf x) + b.
  • In practice: standardize, tune CC and γ\gamma 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.

Question 1

A canonically scaled linear SVM has w=(6,8)\mathbf w = (6, 8). What is the width of its street?

  1. 0.10.1
  2. 0.20.2
  3. 1010
  4. 22
Show the answer

B. 0.20.2

∥w∥=10\norm{\mathbf w} = 10, so the street between f=−1f = -1 and f=+1f = +1 has width 2/∥w∥=0.22/\norm{\mathbf w} = 0.2, and the margin on each side is 0.10.1.

Question 2

In a soft-margin SVM, which training points are support vectors (αi>0\alpha_i > 0)?

  1. Only the misclassified points
  2. Every point inside the street or misclassified, and (typically) the points exactly on the margin: all have yif(xi)≤1y_i f(\mathbf x_i) \le 1
  3. Only points exactly on the margin
  4. All training points
Show the answer

B. Every point inside the street or misclassified, and (typically) the points exactly on the margin: all have yif(xi)≤1y_i f(\mathbf x_i) \le 1

Points with yif(xi)>1y_i f(\mathbf x_i) > 1 have αi=0\alpha_i = 0. Every margin violator, inside the street or misclassified, has αi=C\alpha_i = C. Points exactly on the margin usually have 0<αi≤C0 < \alpha_i \le C; in degenerate cases one can have αi=0\alpha_i = 0.

Question 3

A soft-margin SVM with C=0.1C = 0.1 is trained on n=1,000n = 1{,}000 points. Written as 1n∑i[1−yif(xi)]++λ2∥w∥2\frac1n\sum_i [1 - y_if(\mathbf x_i)]_+ + \frac\lambda2\norm{\mathbf w}^2, what is λ\lambda?

  1. 0.10.1
  2. 100100
  3. 0.010.01
  4. 1010
Show the answer

C. 0.010.01

Dividing 12∥w∥2+C∑iξi\tfrac12\norm{\mathbf w}^2 + C\sum_i\xi_i by nCnC gives λ=1/(nC)=1/(1000×0.1)=0.01\lambda = 1/(nC) = 1/(1000 \times 0.1) = 0.01. Large CC means weak regularization.

Question 4

You raise CC from 0.1 to 1000 on noisy, overlapping data. What typically happens?

  1. The street narrows, fewer points violate the margin, training error falls, and the risk of overfitting grows
  2. The street widens and more points become support vectors
  3. Nothing changes, because CC only affects the dual
  4. 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 CC makes slack expensive, so the optimizer shrinks violations at the cost of a larger ∥w∥\norm{\mathbf w}, a narrower street. That fits the training data more closely, which can help or hurt on new data; cross-validation decides.

Question 5

Why does an RBF-kernel SVM usually need standardized features?

  1. Because the solver only accepts values between −1-1 and 11
  2. Because standardization makes the data linearly separable
  3. It does not: kernels are invariant to the scale of each feature
  4. Because e−γ∥x−z∥2e^{-\gamma\norm{\mathbf x - \mathbf z}^2} depends on Euclidean distances, which a feature with a large numeric range dominates
Show the answer

D. Because e−γ∥x−z∥2e^{-\gamma\norm{\mathbf x - \mathbf z}^2} 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

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).