12 / 27 · Linear Classification
Support vector machines
Among the many lines that separate two classes, the one with the widest margin: the hard-margin problem, slack variables and the soft margin as hinge loss plus an L2 penalty, the Lagrangian, the KKT conditions and the dual derived step by step, what the dual variables say about each training point, how C trades margin for errors, and why a wide margin generalizes.
Linear classifiers and surrogate losses · Regularization · Classification metrics
On this page 16
The linear classifiers note replaced the 0–1 loss by convex surrogates, and the classification metrics note measured how the resulting classifiers err. One question was left open. When the two classes can be separated by a hyperplane, there are infinitely many separating hyperplanes, all with zero training error, and the training loss alone does not say which one to take. Logistic regression answers with probabilities; the support vector machine answers with geometry: take the hyperplane that stays as far as possible from the nearest training points (Boser, Guyon and Vapnik, 1992; Cortes and Vapnik, 1995). This note derives that rule, extends it to classes that overlap, and works out its dual problem, which shows that the solution depends on a few training points only and on nothing but inner products between them. The second fact is what the next note builds on.
Notation. Training points with labels . A linear classifier predicts with weights and bias ; its score is . As in the linear classifiers note, the margin of an example is : positive when is classified correctly. The margin of the hyperplane, , is the distance from the hyperplane to the nearest training point. is the Euclidean norm. Dual variables are and .
Which separating line?#
The maximum-margin line and its support vectors
All three lines in the figure classify the twenty training points correctly. The dotted ones pass within and of a training point; a new point drawn from the same clouds, slightly displaced from its neighbours, can easily land on the wrong side. The solid line keeps a distance of from every training point. The idea of the SVM is to make this distance, the margin of the hyperplane, as large as possible. Why a wide margin generalizes gives the theoretical reason; the intuition is that a classifier whose decision does not change when every training point is moved a little is less likely to be fitting accidents of the sample.
The distance from a point to the hyperplane is
for any on the hyperplane, the distance is the length of the projection of on the unit normal , which is , and . For a hyperplane that classifies every point correctly, , so its margin is .
The hard-margin problem#
Multiplying and by the same positive number changes neither the classifier nor , so one scale can be fixed for free. The SVM fixes it so that the nearest points have : all points satisfy , with equality for the nearest ones. Then , the band between the hyperplanes and contains no training point and has width , and maximizing the margin is minimizing . Squaring and halving make the objective smooth:
This is the hard-margin SVM. The objective is strictly convex in and the constraints are linear, so when the data are separable the optimal is unique, and the problem is a quadratic program that standard solvers handle.
Worked example. Four points: and with , and with . The negative points span the segment , , and the closest positive point to it is , at distance 2. No separating line can be more than half of that, 1, from both classes, and the horizontal line achieves it. In the scaling of the SVM it is , : , , , and . Three points touch the band; does not. The dual will recover the same answer from the other side.
When the classes overlap: slack variables#
Real classes overlap, and then no satisfies all the constraints . The soft-margin SVM (Cortes and Vapnik, 1995) lets each point violate its constraint by a slack and pays per unit of slack:
A point with is on the correct side of its edge of the band; means inside the band but still correctly classified; puts the point on the hyperplane; means on the wrong side of it. Each misclassified point contributes more than 1 to , so the total slack bounds the number of training errors from above. The constant sets the exchange rate between a wide band and few violations: a large makes violations expensive, a small accepts many violations to keep small. On separable data the hard margin is the limit . On overlapping data it is not a limit of anything: the hard-margin constraints have no feasible point, and a larger only makes the unavoidable slack more expensive.
The soft margin is hinge loss plus L2#
For fixed and the best slack is the smallest one allowed: and give . Substituting it removes the constraints:
The first term is the hinge loss of the linear classifiers note, summed over the training set; the second is the ridge penalty of the regularization note. Dividing by gives the familiar form “average loss plus ” with : a large is weak regularization. So the SVM is not a new kind of model but a linear classifier trained with a particular surrogate loss and an L2 penalty. The geometry explains why this particular pair is natural: the penalty measures the inverse width of the band, and the hinge charges only the points that enter it.
The probabilistic reading of the two terms differs. The penalty is the negative log of a Gaussian prior on , as in MAP estimation. The hinge, however, is not a negative log-likelihood. A conditional model would need to be the same for every score , and it is not: at against at . For the logistic loss the same sum is exactly 1, which is why logistic regression outputs probabilities and the SVM does not.
What the hinge does estimate follows from the recipe of other losses, other targets: minimize the expected loss at each separately. With the expected hinge loss of a score is . On it equals , a straight line, and outside that interval it only grows. So the minimizer is when and when : the sign of the Bayes classifier and nothing more (Lin, 2002), the hinge row of the table in what each surrogate estimates. With and the hinge asks for the same score , while the logistic loss asks for the log-odds and . The SVM targets the right decision and discards the confidence; when probabilities are needed, they are fitted afterwards on held-out scores, as in the calibration section of the logistic regression note (Platt, 1999).
The dual problem#
The constrained form is where the structure of the solution shows. The tool is Lagrange duality (Boyd and Vandenberghe, 2004, Chapter 5). Write each constraint as “something ”: and . Give each a multiplier, and , and subtract them from the objective:
Step 1: weak duality. At any feasible both subtracted sums are non-negative, so is at most the objective. Hence the dual function is a lower bound on the optimal value of the SVM problem, for every . The dual problem asks for the best lower bound, .
Step 2: strong duality. The objective is convex and every constraint is affine, and the problem is feasible (, , satisfies all constraints). For such problems the refined Slater condition holds and gives , with the dual optimum attained (Boyd and Vandenberghe, 2004, §5.2.3). Solving the dual therefore solves the SVM.
Step 3: minimize over the primal variables. is a convex quadratic in and linear in and in each . A linear function has a finite minimum only if its slope is zero; otherwise , which is useless as a bound. Setting the derivatives to zero:
Step 4: substitute. With the term in vanishes, with the terms in vanish, and by the first condition:
Step 5: collect the constraints. and together say . The dual of the soft-margin SVM is
It is a concave quadratic program in variables: the matrix is the Gram matrix of the vectors and therefore positive semidefinite. The hard margin gives the same dual without the upper bound . Two features matter for what follows. The data enter only through the inner products . And the solution is read off as , so the classifier is
again a function of inner products only.
The KKT conditions#
Strong duality ties the primal and dual solutions together. At the optimum, , so both inequalities are equalities; the second one forces each subtracted product to be zero. Together with the stationarity of Step 3 and the constraints, these are the Karush–Kuhn–Tucker conditions (Boyd and Vandenberghe, 2004, §5.5.3), necessary and, for a convex problem, sufficient for optimality:
- stationarity: , , ;
- primal feasibility: , ;
- dual feasibility: , ;
- complementary slackness: , .
Complementary slackness says that a multiplier can be non-zero only where its constraint is tight.
Worked example, continued. For the four points, has , so . Stationarity gives , and requires , . Then gives . All multipliers are non-negative, so the KKT conditions hold and , is optimal. The dual objective is , equal to the primal . Summing complementary slackness over the points gives for any hard-margin solution, so the margin can be read from the dual alone: . In the first figure and .
Support vectors: what the dual variables tell you#
The soft margin: what the dual variables say
The KKT conditions sort the training points into three groups by their :
- . Then , so and : the point is on the correct side of its edge of the band. It does not appear in .
- . Then forces , and forces : the point lies exactly on an edge of the band. These points give the bias: and yield , averaged over all such points for numerical stability.
- . Then , may be positive and : the point is on the edge, inside the band, or on the wrong side.
Read backwards: a point strictly outside the band () must have , and a point with positive slack must have . The points with are the support vectors; the solution is a weighted sum of them alone. In the figure 6 of 20 points are support vectors: three on the edges with , and three with and slacks , (inside the band) and (misclassified).
Sparsity has two practical consequences. Deleting a point with and refitting leaves the KKT conditions satisfied by the same and , so the solution does not change; refitting the twenty separable points on their three support vectors alone gives the same line, as the Code section checks. And in leave-one-out validation every point with is classified correctly when held out, since the classifier trained without it is the same and puts it outside the band. The leave-one-out error is therefore at most the number of support vectors divided by , provided the solver returns the same solution when a point with is removed. This bounds the leave-one-out estimate, which, like cross-validation, describes the procedure on training sets of size ; few support vectors are a good sign, but not a finite-sample guarantee for the risk of the one deployed model.
How C trades margin for errors#
On the breast cancer data (569 tumours, 30 standardized features, 70% for training) the choice of moves the solution from a wide band with many violations to a narrow band that fits the training set exactly:
| support vectors | of them with | band width | train accuracy | test accuracy | |
|---|---|---|---|---|---|
| 0.001 | 195 | 189 | 6.38 | 0.940 | 0.930 |
| 0.01 | 92 | 83 | 3.01 | 0.980 | 0.959 |
| 0.1 | 44 | 32 | 1.46 | 0.992 | 0.959 |
| 1 | 27 | 11 | 0.69 | 0.992 | 0.953 |
| 10 | 25 | 3 | 0.32 | 0.995 | 0.953 |
| 100 | 25 | 1 | 0.09 | 1.000 | 0.930 |
With small almost every support vector sits at the bound : the band is wide and many points are inside it. As grows the band narrows, the training accuracy reaches 1, and the test accuracy falls back to : large is weak regularization and overfits, exactly like a small ridge penalty. is a hyperparameter, chosen by cross-validation on a logarithmic grid. Because the band width is measured in the units of the features, the features must be standardized first; otherwise the feature with the largest scale dominates .
Why a wide margin generalizes#
The first generalization bound of the probability course controlled the gap between training and true risk through the number of candidate models. Hyperplanes in are infinitely many, and the classical replacement for grows with : in high dimension, separating the training set says little. Margins remove the dimension. Suppose every input has and the distribution is separable with margin by a hyperplane through the origin. Then with probability at least over a training set of size , the hard-margin SVM has 0–1 risk at most
(Shalev-Shwartz and Ben-David, 2014, Theorem 15.4). The dimension does not appear; only the ratio of the data radius to the margin does. With , and the bound is : loose, as such bounds are, but it holds in a million dimensions as well as in two. This is what makes it reasonable to map the data into a space of enormous dimension and separate it there with a wide margin, the programme of the next note.
Solving it in practice#
The dual has one equality constraint, so the smallest set of variables that can be changed while keeping is a pair. Sequential minimal optimization (Platt, 1998) repeatedly picks two multipliers, solves the two-variable problem in closed form and clips it to the box . LIBSVM, the solver behind scikit-learn’s SVC, takes as the first multiplier the one that most violates the KKT conditions and as the second the one that, paired with it, gives the largest increase of the dual objective, as estimated from second-order information (LIBSVM minimizes the negative of the dual written above, so in its own terms this is the largest decrease) (Fan, Chen and Lin, 2005; Chang and Lin, 2011). The figures of this note are computed by the same method in a few dozen lines. For linear SVMs on large data, the unconstrained hinge-plus-L2 form is minimized directly by stochastic subgradient steps, as in Pegasos (Shalev-Shwartz et al., 2011), whose cost does not grow with for a fixed accuracy. A linear SVM on TF-IDF vectors was for years the standard strong baseline for text classification (Joachims, 1998), the setting of the bag-of-words note of the NLP course.
What changed#
| Logistic regression | Support vector machine | |
|---|---|---|
| Which separating line | the maximum-likelihood one | the one with the widest margin |
| Loss | logistic, smooth, never zero | hinge, zero for |
| Training points that matter | all, each with weight in the gradient | only the support vectors, |
| Output | a probability | a score whose sign is the class; probabilities need calibration |
| Optimization | unconstrained, smooth | a quadratic program, usually solved through its dual |
| Regularization knob | , with | |
| Data enter as | feature vectors | inner products in the dual |
Limitations#
- No probabilities. The hinge loss targets only the sign of ; any probability has to be fitted afterwards, which needs held-out data.
- Sensitive to scale and to . The margin is a Euclidean distance, so features must be standardized, and must be tuned; the table shows test accuracy moving by three points across the grid.
- Outliers still pull. The hinge grows linearly, so a mislabelled point far on the wrong side becomes a support vector with and shifts the solution; the bound limits but does not remove its influence.
- Linear. As written, the SVM separates with a hyperplane in the original features. Two concentric rings of points defeat it, whatever .
- Two classes. Several classes need a reduction to binary problems or a joint formulation; the multiclass note compares them.
What you should remember#
- The distance from to the hyperplane is ; scaling so that the nearest points have makes the margin and the band width .
- Hard margin: minimize subject to . Soft margin: add slacks at price , which is the same as minimizing , hinge loss plus an L2 penalty.
- The dual is subject to , ; strong duality holds, and .
- KKT: outside the band, exactly on its edge (these give ), inside it or misclassified. Only support vectors, , shape the solution.
- Large means weak regularization. The hinge estimates the Bayes decision, not probabilities. Margin bounds depend on , not on the dimension.
Code#
The worked example, the two figures, the dual solved by a generic optimizer, and the effect of :
import numpy as np
from scipy.optimize import minimize
from sklearn.svm import SVC
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def fit(X, y, C):
m = SVC(kernel='linear', C=C, tol=1e-8).fit(X, y)
alpha = np.zeros(len(y)); alpha[m.support_] = np.abs(m.dual_coef_[0]) # dual_coef_ holds y_i * alpha_i
return m.coef_[0], m.intercept_[0], alpha
# the worked example: four points, hard margin (a very large C)
X4 = np.array([[0, 0], [2, 0], [1, 2], [3, 3]]); y4 = np.array([-1, -1, 1, 1])
w, b, alpha = fit(X4, y4, 1e6)
print(w.round(3), round(b, 3), alpha.round(3)) # [0. 1.] -1.0 [0.25 0.25 0.5 0. ]
# twenty separable points (the first figure); class -1 first
Xh = np.array([[-0.9, -0.7], [-1.7, -0.4], [-1.5, -1.9], [-0.6, -1], [-1.9, -0.2], [-2.6, -0.3], [-1.8, -0.7], [-1.7, -0.1], [-1.6, -0.4], [-1.5, -1.2],
[2, 1.5], [0.7, 1.3], [0.4, 0.5], [1.5, -0.4], [0.1, 2.1], [2.8, 2], [0.4, 0.8], [1.5, 0.8], [2.5, 0.3], [0.3, 0.4]])
y = np.repeat([-1, 1], 10)
w, b, alpha = fit(Xh, y, 1e6)
sv = np.flatnonzero(alpha > 1e-6)
print(w.round(3), round(b, 3), round(2 / np.linalg.norm(w), 3), sv, alpha[sv].round(3))
# [0.87 0.87] 0.391 1.626 [ 0 3 19] [0.63 0.126 0.756]
print(round(alpha.sum(), 4), round(w @ w, 4)) # 1.5123 1.5123: at the hard-margin optimum, sum(alpha) = ||w||^2
w2, b2, _ = fit(Xh[sv], y[sv], 1e6)
print(w2.round(3), round(b2, 3)) # [0.87 0.87] 0.391: the support vectors alone give the same line
# twenty overlapping points (the second figure), C = 1
Xs = np.array([[-0.7, -1.3], [-1.6, -0.5], [-0.9, -0.3], [-2.2, -1], [-1.5, 0.1], [-0.4, -0.3], [-0.9, -0.5], [-0.5, -1.3], [0.4, 0.4], [0.7, -0.9],
[1.6, 0.7], [0.1, 1.5], [0.3, 0.3], [1.1, -0.1], [0.4, 1.4], [1.9, 1.2], [1.8, 0.3], [1.7, 1.8], [1.8, -1.3], [2.3, 0.2]])
w, b, alpha = fit(Xs, y, 1.0)
M = y * (Xs @ w + b); xi = np.maximum(0, 1 - M)
print(w.round(3), round(b, 3), np.flatnonzero((alpha > 1e-6) & (alpha < 1 - 1e-6)), np.flatnonzero(alpha > 1 - 1e-6), xi[alpha > 1 - 1e-6].round(2))
# [1.256 0.762] -0.269 [ 5 11 18] [ 8 9 12] [1.54 0.92 0.66]
print(round(0.5 * w @ w + xi.sum(), 4), round(alpha.sum() - 0.5 * w @ w, 4)) # 4.2044 4.2044: primal = dual
# the same dual solved by a generic optimizer: max sum(a) - 1/2 a^T Q a, 0 <= a <= C, sum(a y) = 0
Q = (y[:, None] * Xs) @ (y[:, None] * Xs).T
res = minimize(lambda a: 0.5 * a @ Q @ a - a.sum(), np.zeros(20), jac=lambda a: Q @ a - 1, method='SLSQP',
bounds=[(0, 1)] * 20, constraints={'type': 'eq', 'fun': lambda a: a @ y}, options={'ftol': 1e-12, 'maxiter': 500})
a = res.x; w_dual = (a * y) @ Xs
free = (a > 1e-4) & (a < 1 - 1e-4)
print(w_dual.round(3), round(np.mean(y[free] - Xs[free] @ w_dual), 3)) # [1.256 0.762] -0.269
# the effect of C on breast cancer (569 tumours, 30 standardized features)
X, t = load_breast_cancer(return_X_y=True)
Xtr, Xte, ttr, tte = train_test_split(X, 2 * t - 1, test_size=0.3, random_state=0, stratify=t)
sc = StandardScaler().fit(Xtr); Xtr, Xte = sc.transform(Xtr), sc.transform(Xte)
for C in (0.001, 0.01, 0.1, 1, 10, 100):
m = SVC(kernel='linear', C=C).fit(Xtr, ttr)
at_C = int((np.abs(m.dual_coef_[0]) > C * (1 - 1e-6)).sum())
print(C, len(m.support_), at_C, round(2 / np.linalg.norm(m.coef_[0]), 3), round(m.score(Xtr, ttr), 3), round(m.score(Xte, tte), 3))
# C, support vectors, of them with alpha = C, band width, train and test accuracy
# 0.001 195 189 6.381 0.94 0.93 | 0.01 92 83 3.014 0.98 0.959 | 0.1 44 32 1.459 0.992 0.959
# 1 27 11 0.686 0.992 0.953 | 10 25 3 0.321 0.995 0.953 | 100 25 1 0.089 1.0 0.93
Next#
The dual and the classifier touch the data only through inner products , and the margin bound does not care about the dimension. Both facts point the same way: replace by a richer representation , perhaps of enormous or infinite dimension, and never compute at all, only . The next note shows which functions can play the role of that inner product and what they buy: curved decision boundaries from the same quadratic program.
References#
- B. E. Boser, I. M. Guyon, V. N. Vapnik. A Training Algorithm for Optimal Margin Classifiers. COLT, 1992, pp. 144–152. The hard-margin classifier and its dual.
- C. Cortes, V. Vapnik. Support-Vector Networks. Machine Learning, 20(3), pp. 273–297, 1995. The soft margin.
- S. Boyd, L. Vandenberghe. Convex Optimization. Cambridge University Press, 2004. Chapter 5: the Lagrange dual (§5.1–5.2), Slater’s condition and its refinement for affine constraints (§5.2.3), complementary slackness and the KKT conditions (§5.5.2–5.5.3).
- S. Shalev-Shwartz, S. Ben-David. Understanding Machine Learning: From Theory to Algorithms. Cambridge University Press, 2014. Chapter 15: hard and soft SVM, Theorem 15.4 (the margin bound), §15.3 (support vectors), §15.4 (duality), §15.5 (SGD).
- Y. Lin. Support Vector Machines and the Bayes Rule in Classification. Data Mining and Knowledge Discovery, 6(3), pp. 259–275, 2002. The minimizer of the expected hinge loss.
- J. C. Platt. Probabilistic Outputs for Support Vector Machines and Comparisons to Regularized Likelihood Methods. In A. Smola, P. Bartlett, B. Schölkopf, D. Schuurmans (eds.), Advances in Large Margin Classifiers, pp. 61–74. MIT Press, 1999.
- J. Platt. Sequential Minimal Optimization: A Fast Algorithm for Training Support Vector Machines. Microsoft Research, MSR-TR-98-14, 1998.
- C.-C. Chang, C.-J. Lin. LIBSVM: A Library for Support Vector Machines. ACM Transactions on Intelligent Systems and Technology, 2(3), 2011. Section 4.1: the working set selection.
- R.-E. Fan, P.-H. Chen, C.-J. Lin. Working Set Selection Using Second Order Information for Training Support Vector Machines. Journal of Machine Learning Research, 6, pp. 1889–1918, 2005.
- S. Shalev-Shwartz, Y. Singer, N. Srebro, A. Cotter. Pegasos: Primal Estimated Sub-Gradient Solver for SVM. Mathematical Programming, 127(1), pp. 3–30, 2011.
- T. Joachims. Text Categorization with Support Vector Machines: Learning with Many Relevant Features. ECML, 1998, pp. 137–142.
- C. M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006. Section 7.1 (maximum margin classifiers, overlapping classes, relation to logistic regression), Appendix E (Lagrange multipliers).
- T. Hastie, R. Tibshirani, J. Friedman. The Elements of Statistical Learning, 2nd ed. Springer, 2009. Section 12.2 (the support vector classifier), Section 12.3.2 (the SVM as a penalization method).
- E. Sokolov et al. Машинное обучение (HSE), lecture notes: lecture 5 (the support vector machine), lecture 14 (the dual and the kernel SVM).