Support vector machines: margin, duality and SMO
Derives SVM from the maximum-margin principle, introduces soft margin and hinge loss, and obtains the dual through KKT, revealing support vectors. Implements two real solvers: SMO (Platt) on the dual and Pegasos (stochastic subgradient) on the primal. Prepares for kernels by showing that the dual uses only dot products between examples.
After this lesson you can
- Formulate the hard-margin SVM as a quadratic program and prove that canonical geometric margin is 1/‖w‖.
- Derive the soft-margin SVM dual using KKT and interpret complementary slackness.
- Classify support vectors as free or bound from α and recover b.
- Implement SMO with a pair-selection heuristic and primal Pegasos.
- Relate C to regularized hinge loss and choose it by cross-validation.
Before you start
Motivation: the most robust of infinitely many boundaries
When two classes can be separated by a line, there is almost never just one: there is a continuum. The perceptron keeps the first it finds, depending on data order. Unpenalized logistic regression has no solution at all: in the logistic regression lesson, studying divergence on separable data, you saw grow without bound. Which boundary should you choose?
The support vector machine (SVM) answer is geometric: the boundary leaving the widest corridor between the two classes. Three reasons make it reasonable before seeing any formulas.
- Robustness to perturbations. If the boundary is at least away from every example, any new example within of a training point falls on the same side. A wide corridor tolerates more input noise. This interpretation returns, with another norm, in adversarial examples: for a linear classifier, a perturbation with changes the score by at most .
- Dimension-independent generalization. Margin-based generalization bounds control test error using the ratio of data radius to margin, not the number of features. That is why linear SVMs work on text problems with a hundred thousand features and a few thousand examples.
- Uniqueness. The maximum-margin problem is convex and its solution is unique. It does not depend on data order or initialization.
The method has a long history. The maximum-margin hyperplane dates to Vapnik and collaborators in the 1960s; Boser, Guyon and Vapnik (1992) added kernels and Cortes and Vapnik (1995) added the soft margin, permitting nonseparable data. For a decade it was the state of the art in classification: DeCoste and Schölkopf (2002) reduced MNIST error to 0.56%, below the previous best 0.7%, an ensemble of LeNet4 networks trained on synthetic examples (their table 3). Deep networks later surpassed SVMs in vision and language, but SVM remains an excellent baseline with little data and many features; its hinge loss reappears in network margin losses, and its solution in the implicit bias of gradient descent.
This lesson derives SVM from the margin principle, relaxes it to a soft margin, obtains its dual using the KKT conditions (which yield support vectors), and implements the two practical solution algorithms: SMO on the dual and Pegasos on the primal. At the end you will see that the dual uses only dot products between examples: the gateway to the next lesson’s kernels.
Intuition: the widest corridor
Take ten separable points and find the line leaving the most space on both sides. Move it slightly toward one class and it approaches a point of that class; rotate it and it approaches a point from either class. The only stable positions are those where the line is “wedged” between a few points touching it on both sides of the corridor. These are the support vectors, and the rest do not matter.
In the initial configuration there are three supports: one orange and two blue points. The other seven can move freely outside the corridor without changing the boundary at all, because the solution does not depend on them. This sparsity distinguishes SVM from logistic regression, where each point pulls on the boundary with force that is never exactly zero. The readings also show an identity not yet explained: . It follows from the KKT conditions.
Hard margin: a quadratic program
Functional and geometric margins
Let with . Vector is normal to and the distance from point to is
You will prove this in the first guided exercise; it is the orthogonal projection of onto . If correctly classifies , the absolute value is , giving two measures of a classifier’s margin on the data:
- the functional margin , which depends on scale: multiplying by 10 multiplies it by 10 without moving the boundary;
- the geometric margin , the signed distance from the closest example to the boundary, which is scale invariant: for .
Scale invariance is key. Since and are the same classifier, we can choose any scale. Canonical normalization chooses so that : the nearest points satisfy and lie on hyperplanes . With that normalization the geometric margin is and total corridor width .
The equivalence deserves a line. If is feasible for the program, its geometric margin is at least . Conversely, any separator with rescales to , which is feasible and has . Thus maximizing means minimizing among feasible solutions, and at the optimum some constraint is active (otherwise you could shrink and reduce its norm). Squaring and multiplying by does not change the minimizer and gives a differentiable quadratic objective: a convex quadratic program with linear constraints.
Proof
Existence. The feasible set is a nonempty polyhedron. If is an example of class and one of class , their constraints give , so on the feasible subset with , is also bounded. That subset is compact and nonempty for large , and is continuous: it attains its minimum.
Uniqueness of . If and are optimal with , their midpoint is feasible (the set is convex) and, by strict convexity of , . Contradiction.
Uniqueness of . Fixing , feasible form interval with and . If , with all constraints hold with slack : . Then is feasible and has smaller norm. Contradiction, hence .
∎The cell solves the program with a generic constrained optimizer (SLSQP) on the figure’s initial ten points and compares it with scikit-learn’s SVC using enormous , which, as we shall see, is the hard margin.
import numpy as np
from scipy.optimize import minimize
from sklearn.svm import SVC
# los diez puntos iniciales de «El pasillo más ancho»
X = np.array([[1.4, 1.2], [2.2, 0.6], [2.6, 2.4], [1.6, 3.0], [3.2, 1.2],
[-0.6, 0.6], [0.6, -0.8], [-1.4, -0.4], [-0.4, -2.2], [-2.0, 1.2]])
y = np.array([1, 1, 1, 1, 1, -1, -1, -1, -1, -1], dtype=float)
# primal del margen duro: min ½‖w‖² s.a. y_i (wᵀx_i + b) ≥ 1, con th = (w1, w2, b)
res = minimize(lambda th: 0.5 * th[:2] @ th[:2], x0=np.zeros(3), jac=lambda th: np.r_[th[:2], 0.0],
constraints=[{"type": "ineq", "fun": lambda th: y * (X @ th[:2] + th[2]) - 1,
"jac": lambda th: np.c_[y[:, None] * X, y]}],
method="SLSQP", options={"ftol": 1e-12})
w, b = res.x[:2], res.x[2]
m = y * (X @ w + b)
print("w =", np.round(w, 4), " b =", round(b, 4))
print("margen 1/‖w‖ =", round(1 / np.linalg.norm(w), 4), " anchura 2/‖w‖ =", round(2 / np.linalg.norm(w), 4))
print("y_i f(x_i):", np.round(m, 3))
print("restricciones activas:", np.where(np.abs(m - 1) < 1e-6)[0])
print("distancia mínima a la frontera, min |f(x_i)|/‖w‖ =", round(np.min(np.abs(X @ w + b)) / np.linalg.norm(w), 4))
ref = SVC(kernel="linear", C=1e6, tol=1e-8).fit(X, y)
print("\nSVC(C=1e6): w =", np.round(ref.coef_[0], 4), " b =", round(ref.intercept_[0], 4), " soportes:", ref.support_)
print("alfa de los soportes:", np.round(np.abs(ref.dual_coef_[0]), 4),
" suma =", round(np.abs(ref.dual_coef_[0]).sum(), 4), " ‖w‖² =", round(w @ w, 4))
# un caso degenerado: mueve dos puntos y uno queda en el borde con alfa = 0
Xd = X.copy(); Xd[0] = [1.0, 1.6]; Xd[6] = [0.4, -1.0]
dg = SVC(kernel="linear", C=1e6, tol=1e-10).fit(Xd, y)
md = y * (Xd @ dg.coef_[0] + dg.intercept_[0])
print("\ncaso degenerado: en el borde", np.where(np.abs(md - 1) < 1e-6)[0], " soportes con alfa > 0:", dg.support_,
" alfa:", np.round(np.abs(dg.dual_coef_[0]), 4))Both approaches give and , with margin and corridor width . There are exactly three active constraints, points 0, 5 and 6 (zero-indexed), the three supports of SVC, and their multipliers sum to . The minimum distance of the ten points to the boundary equals the margin, as it should.
Soft margin: slacks, C and the hinge
Move a point across in the previous figure and the hard margin ceases to exist: no is feasible. Even if the data are separable, one outlier can narrow the corridor until useless. Cortes and Vapnik’s solution allows each example to violate its constraint at a price.
Each slack has a direct geometric interpretation. With the example is outside the corridor or on its edge. With it is inside the corridor but on its side of the boundary ( means exactly on it). With it is misclassified. If , the distance from the example to its corridor edge is , so bounds the number of training errors: each error contributes more than 1. Parameter sets the exchange between the two currencies, corridor width and violations.
Given , optimal slack is the smallest compatible with both constraints, : exactly the example’s hinge loss. Eliminating slacks gives the form connecting SVM to what you already know.
The proof is the third guided exercise. The result places SVM in the same family as ridge regression and penalized logistic regression: empirical loss plus L2 penalty, changing only the loss. It also clarifies : it is inverse regularization strength, . Large means weak regularization; small , strong. Intercept is not penalized.
import numpy as np
from sklearn.svm import SVC
rng = np.random.default_rng(4)
X2 = np.round(np.vstack([rng.normal([0.9, 0.7], 0.9, size=(20, 2)),
rng.normal([-0.9, -0.5], 0.9, size=(20, 2))]), 2)
y2 = np.r_[np.ones(20), -np.ones(20)]
print(f"{'C':>7} {'soportes':>8} {'libres':>6} {'en C':>5} {'anchura':>8} {'errores':>7} {'Σξ':>7} {'objetivo':>9}")
for C in [0.01, 0.1, 1, 10, 100, 1000]:
m = SVC(kernel="linear", C=C, tol=1e-6).fit(X2, y2)
a = np.zeros(len(y2)); a[m.support_] = np.abs(m.dual_coef_[0])
w, b = m.coef_[0], m.intercept_[0]
xi = np.maximum(0, 1 - y2 * (X2 @ w + b)) # holguras óptimas: la bisagra de cada punto
libres = ((a > 1e-7 * C) & (a < C * (1 - 1e-7))).sum()
print(f"{C:7g} {len(m.support_):8d} {libres:6d} {(a >= C * (1 - 1e-7)).sum():5d} {2 / np.linalg.norm(w):8.3f} "
f"{(np.sign(X2 @ w + b) != y2).sum():7d} {xi.sum():7.3f} {0.5 * w @ w + C * xi.sum():9.3f}")
# con C muy grande, ¿qué queda? La frontera que minimiza solo Σ ξ_i: un programa lineal en (w, b, ξ)
from scipy.optimize import linprog
n2 = len(y2)
lp = linprog(np.r_[0, 0, 0, np.ones(n2)], A_ub=np.c_[-y2[:, None] * X2, -y2, -np.eye(n2)], b_ub=-np.ones(n2),
bounds=[(None, None)] * 3 + [(0, None)] * n2, method="highs")
print(f"\nmin Σ ξ_i = {lp.fun:.4f} en w = {np.round(lp.x[:2], 3)}, b = {lp.x[2]:.3f}")
for C in [300, 400, 1000]:
m = SVC(kernel="linear", C=C, tol=1e-6).fit(X2, y2)
print(f"SVC con C = {C:4d}: w = {np.round(m.coef_[0], 3)}, b = {m.intercept_[0]:.3f}")The table summarizes the figure. With the corridor measures and 38 of 40 points are supports, all at the bound: the penalty dominates and the model barely looks at data. As increases the corridor narrows, supports decrease (23, 13, 8, 5, 4), and the sum of slacks also falls, while the objective grows because each slack unit costs more. With the corridor measures : the model has rotated to leave almost all obstructing points outside it, and four points determine the boundary. Training errors do not decrease monotonically (5, 5, 2, 1, 2, 1): SVM minimizes slacks, not errors.
The last output lines explain why the figure’s width curve flattens on the right. With and , SVC returns the same , exactly the minimizer of alone, which the cell computes as a linear program. This is no coincidence. When the minimizer of the hinge sum is unique, as here, grows at least linearly away from it: for some (piecewise-linear convex functions with a unique minimum have a “sharp” minimum). And . Adding these, for the objective is strictly greater than at for any : beyond a finite the solution no longer changes. Which is best? None of these numbers says: cross-validation is needed, and you will do it at the end.
The dual problem
Lagrangian and hard-margin dual
The primal program has variables and constraints. Its dual swaps roles and, above all, reveals solution structure. With multiplier per constraint, the hard-margin Lagrangian is
The dual function is . For each , is a convex quadratic in plus a linear term in :
- In : , hence .
- In : the coefficient of is . If nonzero, the infimum is (take to ), so the dual is useful only where .
Substituting and using , the term in disappears and
The soft-margin dual
This is the SVM dual problem. Compared with hard margin, the only addition is the upper bound , arising from slacks; the complete derivation is the second guided exercise. In matrix notation, with , the dual is over the intersection of a box with a hyperplane: a QP with variables, concave because with rows is positive semidefinite.
Strong duality needs no extra condition: the primal is a convex QP with affine constraints and is always feasible (take sufficiently large ), and for such problems the refined Slater condition requires only feasibility (strong duality). Consequently KKT conditions are necessary and sufficient: feasible is optimal if and only if some exists that, together with and slacks , satisfies them.
Complementary slackness and support vectors
The soft-margin KKT conditions, with multipliers for margin constraints and for , are:
- Stationarity: , , .
- Feasibility: , , , .
- Complementary slackness: and .
Complementary slackness divides examples into three groups by , and this classification is the lesson’s central result.
| KKT implication | Example location | Name | |
|---|---|---|---|
| , hence | outside corridor or on edge | not a support | |
| , and | exactly on edge | free support | |
| on edge, inside corridor or misclassified | bound support |
The last claim follows directly: without that coordinate still satisfies every KKT condition of the reduced problem, which is sufficient. Read backwards, the table yields diagnostic implications: if , then ; if , then . What cannot be inferred is the converse of the first row: a point exactly on the edge may have any . This happens in degenerate configurations. The last part of the hard-margin cell constructs one: with the orange support at and the lower blue one at , that blue point lies exactly on the edge but has , and only two supports hold the boundary.
Recovering . Each free support satisfies , and since , . Exactly, they all give the same value; in floating point they are averaged. If there are no free supports (this happens with small : in the SMO cell you will see a case with and 14 supports, all bound), KKT only says lies in an interval and any point in it is optimal: is not unique even though is. LIBSVM takes the midpoint.
Two identities. Summing complementary slackness, . The left side is , and because forces . Therefore
In the hard margin all slacks are zero, leaving : the first figure’s identity, confirmed by the hard-margin cell ( on both sides). In the soft margin, substituting into the primal, : strong duality checked by hand.
Hard margin is a soft-margin case. If data are separable and is the hard-margin dual solution, for every that same vector is feasible for the soft dual and satisfies its KKT conditions with , . Thus soft margin with sufficiently large is hard margin, not an approximation. That is why the corridor figure uses SMO with and the cell compares with SVC(C=1e6).
Hinge versus logistic: sparse solutions
Logistic regression with the same penalty, with , has an optimality condition of the same form as SVM. Setting the gradient in to zero,
The difference is in the weights: is small for large margins but never zero. Hinge loss, by contrast, is exactly flat from onward and produces exactly zero weights.
With the twelve initial points at , the SVM boundary does not move and the added points’ are exactly 0, while logistic regression rotates several degrees because each added point contributes a positive . The weight panel shows the full structure: SVM bars appear only on the left, at points with margin at most 1, and equal for those violating the margin; logistic points decrease smoothly to the right without reaching zero. As soon as falls below 1, added points enter the corridor, their hinge ceases to be zero and SVM moves too: what matters is being outside the corridor, not merely correctly classified.
SMO: optimizing two multipliers at a time
The dual has variables and matrix has entries: with , eighty gigabytes in float64. In 1998 generic QP solvers did not even fit in memory and “chunking” methods solved a sequence of increasingly large subproblems. Platt’s (1998) idea was to take decomposition to the extreme: optimize the smallest possible number of variables, two, at each step, because the two-variable subproblem has an analytical solution and needs no solver.
Why two rather than one? Because of equality constraint . If you change one leaving the rest fixed, cannot change, so neither can . With two, the constraint leaves a line: constant. The SMO algorithm (sequential minimal optimization) is block coordinate descent on the dual, with blocks of size two.
The analytical step
Write prediction without intercept as , with , and each example’s error as . To move along the constraint line, change and : sum changes by . Call that direction (, , rest zero).
- Slope. The dual gradient is , with . Then . Intercept cancels in the subtraction.
- Curvature. with and , giving .
Since is quadratic, it is exactly a parabola along the line:
If , its maximum is at , giving Platt’s formula
The box remains. Both coordinates must stay in , restricting to interval :
- if (the line is constant ): , ;
- if (the line is constant ): , .
Because the parabola is concave, its segment maximum is the clipped free maximum: . Then , maintaining the line. With a linear kernel, only if ; then is linear along the line and the maximum lies at an endpoint, which Platt chooses by evaluating the objective at both.
Which pair to choose
Any pair with and some room for improvement raises the objective, but order matters enormously. Platt proposed two heuristics: an outer loop over examples violating KKT (alternating passes over the whole set and free supports, which tend to change most) and, for the first chosen index , a second maximizing , a cheap approximation to step size. KKT conditions are checked with a tolerance; Platt writes that it is “typically” and that an output between and at a boundary point is acceptable for recognition.
The rule used today by LIBSVM and scikit-learn follows from rewriting KKT. Call the value of that would put example exactly on its edge. Reviewing the table’s three cases for each class, KKT says for the in
and for those in . Such an exists if and only if
The difference is the maximum KKT violation, and its pair , is Keerthi et al.’s (2001) maximum-violation pair. For that pair, slope of the parabola equals exactly (remember ): choosing it selects, among all two-coordinate directions respecting constraints, the steepest ascent direction, and the natural stopping criterion is . Keerthi and Gilbert (2002) proved that with this rule SMO terminates in finitely many steps for any . LIBSVM uses a second-order version (Fan, Chen and Lin, 2005): it takes the same , but chooses by the gain from the unclipped step, , accounting for curvature as well as slope. Its default tolerance is , the tol of SVC.
At the optimum, and may be any point of ; in practice the mean of free-support is used if any exist, otherwise midpoint .
SMO from scratch
import numpy as np
from sklearn.svm import SVC
def smo(X, y, C, tol=1e-3, max_iter=100_000, pares="mvp", seed=0, snap=True):
"""SMO para el SVM lineal. Devuelve alfa, w, b, el número de pasos y la violación final."""
n = len(y)
K = X @ X.T
a = np.zeros(n)
G = -np.ones(n) # gradiente de f(a) = ½ aᵀQa − 1ᵀa = −D(a)
rng = np.random.default_rng(seed)
for it in range(max_iter + 1):
s = -y * G # s_t = y_t − f₀(x_t)
up = ((y > 0) & (a < C)) | ((y < 0) & (a > 0))
low = ((y > 0) & (a > 0)) | ((y < 0) & (a < C))
i = np.argmax(np.where(up, s, -np.inf))
j = np.argmin(np.where(low, s, np.inf))
gap = s[i] - s[j] # máxima violación m(α) − M(α)
if gap < tol or it == max_iter:
break
if pares == "azar":
i, j = rng.choice(n, 2, replace=False)
Ei, Ej = y[i] * G[i], y[j] * G[j] # E_t − b = f₀(x_t) − y_t
eta = K[i, i] + K[j, j] - 2 * K[i, j]
if y[i] != y[j]:
L, H = max(0.0, a[j] - a[i]), min(C, C + a[j] - a[i])
else:
L, H = max(0.0, a[i] + a[j] - C), min(C, a[i] + a[j])
aj = min(max(a[j] + y[j] * (Ei - Ej) / max(eta, 1e-12), L), H)
ai = a[i] + y[i] * y[j] * (a[j] - aj)
if snap: # lleva a la cota exacta lo que está a menos de 1e-12·C de ella
ai = 0.0 if ai < 1e-12 * C else (C if ai > C * (1 - 1e-12) else ai)
aj = 0.0 if aj < 1e-12 * C else (C if aj > C * (1 - 1e-12) else aj)
G += y * (y[i] * K[:, i] * (ai - a[i]) + y[j] * K[:, j] * (aj - a[j]))
a[i], a[j] = ai, aj
s = -y * G
libres = (a > 1e-9 * C) & (a < C * (1 - 1e-9))
if libres.any():
b = s[libres].mean() # y_t f(x_t) = 1 en los libres
else:
up = ((y > 0) & (a < C)) | ((y < 0) & (a > 0))
low = ((y > 0) & (a > 0)) | ((y < 0) & (a < C))
b = (s[up].max() + s[low].min()) / 2
return a, (a * y) @ X, b, it, gap
def objetivo_dual(a, X, y):
v = (a * y) @ X
return a.sum() - 0.5 * v @ v
# los 20 puntos de «SMO paso a paso»
rng = np.random.default_rng(0)
X3 = np.round(np.vstack([rng.normal([0.9, 0.7], 0.9, size=(10, 2)),
rng.normal([-0.9, -0.5], 0.9, size=(10, 2))]), 2)
y3 = np.r_[np.ones(10), -np.ones(10)]
for C in [0.1, 1.0, 10.0]:
a, w, b, it, gap = smo(X3, y3, C)
ref = SVC(kernel="linear", C=C).fit(X3, y3)
libres = ((a > 1e-9 * C) & (a < C * (1 - 1e-9))).sum()
print(f"C = {C:4}: {it:3d} pasos, w = {np.round(w, 3)}, b = {b:+.3f}, soportes {np.sum(a > 0)} "
f"({libres} libres, {np.sum(a == C)} en C), D = {objetivo_dual(a, X3, y3):.4f}")
print(f" SVC: w = {np.round(ref.coef_[0], 3)}, b = {ref.intercept_[0]:+.3f}, soportes {len(ref.support_)}")
pasos = [smo(X3, y3, 1.0, pares="azar", seed=s)[3] for s in range(20)]
print("\npares al azar, C = 1, 20 semillas: mediana", int(np.median(pasos)), "pasos (mín", min(pasos), ", máx", max(pasos), ")")With , SMO using maximum violation converges in 18 steps with 11 supports (3 free and 8 bound), the same as SVC; and differ from SVC in the third decimal, expected given tolerance and two different selection rules. With all supports are bound and comes from the interval midpoint, yet agrees with SVC, which uses the same rule. With it takes 118 steps: large makes the box wider and travel farther. With random pairs the same exact update takes a median 1388 steps (785 to 3043 by seed): selection is worth two orders of magnitude.
Now the same code on a real problem: breast_cancer (569 tumors, 30 features), with features standardized using training mean and standard deviation.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
Xbc, ybc = load_breast_cancer(return_X_y=True)
ybc = np.where(ybc == 1, 1.0, -1.0)
Xtr0, Xte0, ytr, yte = train_test_split(Xbc, ybc, test_size=0.3, random_state=0, stratify=ybc)
esc = StandardScaler().fit(Xtr0)
Xtr, Xte = esc.transform(Xtr0), esc.transform(Xte0)
print("entrenamiento:", Xtr.shape, " prueba:", Xte.shape)
for C in [0.1, 1.0]:
a, w, b, it, gap = smo(Xtr, ytr, C)
ref = SVC(kernel="linear", C=C).fit(Xtr, ytr)
a_ref = np.zeros(len(ytr)); a_ref[ref.support_] = np.abs(ref.dual_coef_[0])
cos = w @ ref.coef_[0] / np.linalg.norm(w) / np.linalg.norm(ref.coef_[0])
print(f"C = {C}: SMO {it} pasos, {np.sum(a > 0)} soportes, D = {objetivo_dual(a, Xtr, ytr):.5f}, "
f"b = {b:+.4f}, acierto {np.mean(np.sign(Xte @ w + b) == yte):.4f}")
print(f" SVC {len(ref.support_)} soportes, D = {objetivo_dual(a_ref, Xtr, ytr):.5f}, "
f"b = {ref.intercept_[0]:+.4f}, acierto {ref.score(Xte, yte):.4f}, coseno(w, w_SVC) = {cos:.6f}")
a, w, b, it, gap = smo(Xtr, ytr, 1.0, max_iter=3000, snap=False)
print(f"\nsin llevar los α a la cota: {it} pasos, violación {gap:.3f}, D = {objetivo_dual(a, Xtr, ytr):.4f}")
casi = (a > 0) & (a < 1e-12)
print("alfas positivos pero menores que 1e-12:", np.sum(casi), " por ejemplo", a[casi][:2])With it takes 2203 steps and matches SVC: 27 supports, the same dual objective to five decimals, equal to three decimals, and cosine between the two . The last part shows why the function snaps to the exact bound. Without doing so, subtraction leaves instead of 0 due to rounding; that example, which should be at the bound, still counts as “” and enters the set of those able to decrease ; the rule chooses it repeatedly, but the step would require and clipping leaves it unchanged; SMO gets stuck with violation and objective versus . LIBSVM avoids this by assigning the exact bound when one variable reaches it, rather than obtaining it by subtraction.
Duality gap as a stopping criterion
Maximum violation is convenient, but how far is the objective really from optimal? Weak duality gives a guaranteed answer: for any feasible and any , , and they are equal at the optimum. Thus bounds both the dual’s shortfall and the primal’s excess. During SMO, current gives a primal, and it is useful to choose the best for that : is convex and piecewise linear in , so its minimum lies at one of the breakpoints .
import numpy as np
import matplotlib.pyplot as plt
def primal_mejor_b(f0, y, C):
"""min_b C Σ max(0, 1 − y_i(f0_i + b)): se evalúa en todos los puntos de quiebre."""
cand = y - f0
perdidas = np.maximum(0, 1 - y[None, :] * (f0[None, :] + cand[:, None])).sum(axis=1)
k = np.argmin(perdidas)
return cand[k], C * perdidas[k]
def smo_traza(X, y, C, tol=1e-6, max_iter=20_000, cada=10):
n = len(y); K = X @ X.T
a = np.zeros(n); G = -np.ones(n)
violacion, traza = [], []
for it in range(max_iter + 1):
s = -y * G
up = ((y > 0) & (a < C)) | ((y < 0) & (a > 0))
low = ((y > 0) & (a > 0)) | ((y < 0) & (a < C))
i = np.argmax(np.where(up, s, -np.inf)); j = np.argmin(np.where(low, s, np.inf))
violacion.append(s[i] - s[j])
if it % cada == 0 or violacion[-1] < tol:
w = (a * y) @ X
_, perdida = primal_mejor_b(X @ w, y, C)
traza.append((it, 0.5 * w @ w + perdida, a.sum() - 0.5 * w @ w)) # (paso, P, D)
if violacion[-1] < tol:
break
Ei, Ej = y[i] * G[i], y[j] * G[j]
eta = K[i, i] + K[j, j] - 2 * K[i, j]
L, H = ((max(0.0, a[j] - a[i]), min(C, C + a[j] - a[i])) if y[i] != y[j]
else (max(0.0, a[i] + a[j] - C), min(C, a[i] + a[j])))
aj = min(max(a[j] + y[j] * (Ei - Ej) / max(eta, 1e-12), L), H)
ai = a[i] + y[i] * y[j] * (a[j] - aj)
ai = 0.0 if ai < 1e-12 * C else (C if ai > C * (1 - 1e-12) else ai)
aj = 0.0 if aj < 1e-12 * C else (C if aj > C * (1 - 1e-12) else aj)
G += y * (y[i] * K[:, i] * (ai - a[i]) + y[j] * K[:, j] * (aj - a[j]))
a[i], a[j] = ai, aj
return a, np.array(violacion), np.array(traza)
C = 1.0
a, viol, tr = smo_traza(Xtr, ytr, C)
it, P, D = tr.T
rel = (P - D) / P
print("pasos hasta violación < 1e-6:", len(viol) - 1, " P =", round(P[-1], 6), " D =", round(D[-1], 6))
print("¿P − D ≥ 0 en todos los pasos registrados?", bool(np.all(P - D >= -1e-9)))
for umbral in [1e-1, 1e-2, 1e-3]:
k = int(np.argmax(viol < umbral)) # primer paso con violación < umbral
r = rel[np.argmin(np.abs(it - k))] # brecha registrada más próxima
print(f"violación < {umbral:g} por primera vez en el paso {k:5d}: brecha relativa (P − D)/P ≈ {r:.1e}")
# KKT punto a punto en la solución
w = (a * ytr) @ Xtr
b, _ = primal_mejor_b(Xtr @ w, ytr, C)
m = ytr * (Xtr @ w + b)
cero, cota = a == 0, a == C
libre = ~cero & ~cota
print(f"\nα = 0 : {cero.sum():3d} puntos, min y f(x) = {m[cero].min():.4f} (KKT: ≥ 1)")
print(f"0 < α < C: {libre.sum():3d} puntos, max |y f(x) − 1| = {np.abs(m[libre] - 1).max():.1e} (KKT: = 1)")
print(f"α = C : {cota.sum():3d} puntos, max y f(x) = {m[cota].max():.4f} (KKT: ≤ 1)")
fig, ax = plt.subplots(1, 2, figsize=(9, 3.2))
ax[0].plot(it, P, label="primal P(w) con el mejor b"); ax[0].plot(it, D, label="dual D(α)")
ax[0].set_ylim(0, 2 * P[-1]); ax[0].set_xlabel("paso de SMO"); ax[0].legend()
ax[1].semilogy(it, rel, label="brecha relativa (P − D)/P")
ax[1].semilogy(np.arange(len(viol)), viol, lw=0.6, label="máxima violación m − M")
ax[1].axhline(1e-3, color="gray", ls="--", lw=1); ax[1].set_xlabel("paso de SMO"); ax[1].legend()
plt.tight_layout(); plt.show()The gap is never negative, as weak duality requires, and the two convergence measures fall together but are not the same. Maximum violation is a bound in output units (“no point is more than away from satisfying KKT”), while relative gap measures objective shortfall. In this run, the first time violation falls below (LIBSVM’s default criterion) the relative gap is already of order : the standard criterion solves the objective to four digits. Pointwise checking of the final solution reproduces the complementary-slackness table: the 371 points with have , the 16 free ones are on the edge with error below and the 11 bound ones have .
Pegasos: stochastic subgradient on the primal
SMO needs the errors in memory, and updating them each step costs kernel evaluations. When is in the millions and the model is linear, working on the primal with one example at a time is cheaper. The hinge-form objective,
is not differentiable where , but is convex and -strongly convex. The Pegasos algorithm of Shalev-Shwartz, Singer, Srebro and Cotter (2011) is the stochastic subgradient method with a step adapted to that strong convexity. At step :
- Choose randomly from and take .
- A subgradient of the objective at that example is , so
- (Optional) Project onto the ball of radius : .
With , factor turns the recursion into an average. By induction,
the iterate is a scaled sum of examples that violated the margin when selected. It has the same form as the dual, so Pegasos also supports kernels.
Projection does not change the optimum, because . On this form’s scale, the previous section’s dual is written with and , and strong duality gives .
What it guarantees. The paper’s main result is that the number of steps to precision is , versus from earlier stochastic-gradient analyses for SVM; with sparse data having nonzero entries per example, total time is and does not depend on . Specifically (corollary 2), with probability at least the mean iterate satisfies , with without projection and . This is SGD’s rate for strongly convex objectives (convex SGD convergence), with the specific hinge constant. Two observations from the paper: the bound is for the mean, but in experiments the last iterate worked better and was used, and the authors saw no important differences between projected and unprojected versions.
The intercept. Pegasos is formulated without . Section 6 discusses three ways to add it: as a constant feature equal to 1 (simple, but then is penalized and it is a different problem), in the loss without penalizing it (the objective ceases to be strongly convex in and the guarantee drops to ), or with an outer search loop over . The first is what LIBLINEAR uses (LinearSVC, with its intercept_scaling) and what we use here.
In the figure, the first steps are violent: with , and the first iterate is , far from anything reasonable. The mean carries those first iterates for a long time and therefore trails the last for almost the entire path; eventually they meet. Both descend with slope near , the rate, with much more noise for the last iterate. Lowering shifts the curves up: more time is needed, as the bound says.
import numpy as np
from sklearn.svm import LinearSVC
from sklearn.linear_model import SGDClassifier
def pegasos(Z, y, lam, T, seed=0, proyectar=False, guardar=()):
"""Pegasos con un ejemplo por paso. Devuelve {t: (último iterado, media de los iterados)}."""
rng = np.random.default_rng(seed)
idx = rng.integers(0, len(y), T)
v = np.zeros(Z.shape[1]); suma = np.zeros_like(v); out = {}
radio = 1 / np.sqrt(lam)
for t in range(1, T + 1):
i = idx[t - 1]
eta = 1 / (lam * t)
viola = y[i] * (Z[i] @ v) < 1 # se evalúa con el v anterior
v *= 1 - eta * lam # paso del regularizador
if viola:
v += eta * y[i] * Z[i] # subgradiente de la bisagra
if proyectar:
nv = np.linalg.norm(v)
if nv > radio:
v *= radio / nv
suma += v
if t in guardar:
out[t] = (v.copy(), suma / t)
return out
C = 1.0
n = len(ytr)
lam = 1 / (n * C) # el problema de C = 1, con el sesgo como característica
Ztr, Zte = np.c_[Xtr, np.ones(n)], np.c_[Xte, np.ones(len(yte))]
F = lambda v: 0.5 * lam * v @ v + np.maximum(0, 1 - ytr * (Ztr @ v)).mean()
ref = LinearSVC(loss="hinge", C=C, tol=1e-8, max_iter=100_000).fit(Xtr, ytr) # LIBLINEAR, mismo objetivo
v_ref = np.r_[ref.coef_[0], ref.intercept_[0]]
print(f"λ = {lam:.5f} F* (LinearSVC) = {F(v_ref):.5f} acierto de LinearSVC = {ref.score(Xte, yte):.4f}")
for proy in [False, True]:
res = pegasos(Ztr, ytr, lam, 100_000, proyectar=proy, guardar=(1_000, 10_000, 100_000))
for T, (v, vm) in res.items():
print(f"proyección {'sí' if proy else 'no'}, T = {T:>6}: (F − F*)/F* último {(F(v) - F(v_ref)) / F(v_ref):.3f}, "
f"media {(F(vm) - F(v_ref)) / F(v_ref):.3f} acierto {np.mean(np.sign(Zte @ v) == yte):.4f}")
sgd = SGDClassifier(loss="hinge", alpha=lam, max_iter=1000, tol=1e-6, random_state=0).fit(Xtr, ytr)
print(f"\nSGDClassifier(loss='hinge', alpha=λ): {sgd.n_iter_} épocas, acierto {sgd.score(Xte, yte):.4f}")
# los cuarenta puntos sintéticos de «El camino de C», con C = 1
lam2 = 1 / len(y2)
Z2 = np.c_[X2, np.ones(len(y2))]
F2 = lambda v: 0.5 * lam2 * v @ v + np.maximum(0, 1 - y2 * (Z2 @ v)).mean()
ref2 = LinearSVC(loss="hinge", C=1.0, tol=1e-10, max_iter=100_000).fit(X2, y2)
v2 = np.r_[ref2.coef_[0], ref2.intercept_[0]]
ult, med = pegasos(Z2, y2, lam2, 20_000, guardar=(20_000,))[20_000]
print(f"sintéticos, T = 20000: v Pegasos = {np.round(ult, 3)}, v LinearSVC = {np.round(v2, 3)}, (F − F*)/F* = {(F2(ult) - F2(v2)) / F2(v2):.4f}")With , the last iterate’s relative excess falls from to and across , and steps: a factor 26 in the first decade, still carrying the initial phase, and a factor 8 in the second, already close to the rate. The mean trails (, and ), as in the figure and as the authors observed, and projection barely changes the end. In test accuracy Pegasos already matches LinearSVC after steps (25 epochs), although its objective is still 21% higher: classification does not require solving the problem to many digits. Scikit-learn’s SGDClassifier(loss="hinge") is essentially this algorithm: its default schedule learning_rate="optimal" is with Bottou’s heuristic , and its alpha is our (although it does not penalize the intercept). On the forty synthetic points, fitting in one epoch of 40 steps, 20,000 steps (500 epochs) leave relative excess and an differing from LinearSVC by less than in each component.
Multiclass and probabilities
SVM is binary. For classes there are two standard constructions:
- One versus rest (OvR): classifiers, the -th trained on class versus all others, predicting . Scores from different classifiers do not share a scale, so is a heuristic. This is what
LinearSVCdoes. - One versus one (OvO): classifiers, one per class pair and trained only on those two classes’ examples, predicting by vote. There are many more models but each uses far fewer data points, and since SMO cost grows faster than , it is often cheaper.
SVCalways does this: itsdecision_function_shape="ovr"merely rearranges OvO scores into one column per class.
There are also single-problem formulations for all classes (Crammer and Singer, in LinearSVC(multi_class="crammer_singer")), which scikit-learn documentation describes as rarely more accurate and more expensive.
SVM scores are not probabilities: hinge loss estimates only the sign of , as you saw in the loss lesson. If probabilities are needed, fit a monotonic transformation on data unseen by the model; the most common is lesson 22’s Platt scaling, a sigmoid . SVC(probability=True) did this with internal five-fold cross-validation, and since scikit-learn 1.9 is deprecated in favor of CalibratedClassifierCV.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC, LinearSVC
from sklearn.multiclass import OneVsRestClassifier
from sklearn.calibration import CalibratedClassifierCV
Xd, yd = load_digits(return_X_y=True) # 1797 imágenes de 8x8, 10 clases
Xd_tr, Xd_te, yd_tr, yd_te = train_test_split(Xd / 16.0, yd, test_size=0.3, random_state=0, stratify=yd)
ovo = SVC(kernel="linear", C=1.0, decision_function_shape="ovo").fit(Xd_tr, yd_tr)
ovr = OneVsRestClassifier(SVC(kernel="linear", C=1.0)).fit(Xd_tr, yd_tr)
lin = LinearSVC(C=1.0, loss="hinge", max_iter=50_000).fit(Xd_tr, yd_tr)
print("OvO con SVC: ", ovo.decision_function(Xd_te[:1]).shape[1], "clasificadores, acierto", round(ovo.score(Xd_te, yd_te), 4))
print("OvR con SVC: ", len(ovr.estimators_), "clasificadores, acierto", round(ovr.score(Xd_te, yd_te), 4))
print("OvR con LinearSVC: ", lin.decision_function(Xd_te[:1]).shape[1], "clasificadores, acierto", round(lin.score(Xd_te, yd_te), 4))
cal = CalibratedClassifierCV(LinearSVC(C=1.0, loss="hinge", max_iter=50_000), method="sigmoid", cv=5).fit(Xd_tr, yd_tr)
print("\npuntuaciones de LinearSVC, primer ejemplo de prueba:", np.round(lin.decision_function(Xd_te[:1])[0], 2))
print("probabilidades tras el escalado de Platt: ", np.round(cal.predict_proba(Xd_te[:1])[0], 3))
print("clase verdadera:", yd_te[0], " acierto del calibrado:", round(cal.score(Xd_te, yd_te), 4))With the same base SVM, OvO (45 classifiers) achieves and OvR (10 classifiers) ; LinearSVC, also OvR, reaches . In this problem comparing only two classes at a time suits linear SVM better than separating each digit from all others at once. In the first test example two scores are positive and similar: an OvR SVM does not say how much more likely one is than another, whereas the calibrated version distributes probability between those two classes and almost none to the others.
The professional version: SVC, LinearSVC and SGDClassifier
| Class | Library and algorithm | Loss and intercept | When |
|---|---|---|---|
SVC(kernel="linear") | LIBSVM: SMO with second-order selection, kernel cache | hinge; unpenalized | up to tens of thousands; need or will use kernels |
LinearSVC | LIBLINEAR: dual coordinate descent (Hsieh et al., 2008) or primal Newton | squared hinge by default; as penalized feature | linear model with large or sparse data |
SGDClassifier(loss="hinge") | SGD with | hinge; unpenalized | huge , online learning (partial_fit) |
Three details of this table cause surprises. First, LinearSVC() without arguments is not this lesson’s SVM: it uses loss="squared_hinge" and penalizes the intercept, yielding a different solution from SVC(kernel="linear"). To bring them closer, loss="hinge" and a large intercept_scaling. Second, LIBLINEAR coordinate descent can move one at a time precisely because treating as another feature removes constraint from the dual: it is SMO without the reason for pairs. Third, SVC solves the dual, whose cost grows at least quadratically with ; its documentation says so and recommends the other two classes for large datasets.
Choosing C by cross-validation
is a hyperparameter, and its useful value depends on data scale and . The practical guide by Hsu, Chang and Lin, LIBSVM’s authors, recommends scaling each feature and searching on an exponential grid ( in their example) with cross-validation. Scaling goes inside a pipeline so each fold fits it on its own training data.
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV, StratifiedKFold
pipe = make_pipeline(StandardScaler(), SVC(kernel="linear"))
rejilla = {"svc__C": 2.0 ** np.arange(-10, 7, 2)}
gs = GridSearchCV(pipe, rejilla, cv=StratifiedKFold(5, shuffle=True, random_state=0)).fit(Xtr0, ytr) # datos sin escalar
for C, mu, sd in zip(rejilla["svc__C"], gs.cv_results_["mean_test_score"], gs.cv_results_["std_test_score"]):
nsv = make_pipeline(StandardScaler(), SVC(kernel="linear", C=C)).fit(Xtr0, ytr)[-1].n_support_.sum()
print(f"C = 2^{int(np.log2(C)):>3}: acierto CV {mu:.4f} ± {sd:.4f} soportes {nsv}")
print("mejor C =", gs.best_params_["svc__C"], " acierto en prueba =", round(gs.score(Xte0, yte), 4))The curve has the usual shape: with the model is overregularized (93.0% and 197 supports), the maximum is at (99.25% cross-validation accuracy), and accuracy then falls slowly while support count plateaus around 24. The selected achieves 94.7% test accuracy, below validation: with 171 test examples the difference is around 8 errors, and a grid maximum is an optimistic estimate (as in validation overfitting).
The dual’s cost
import time
import numpy as np
from sklearn.svm import SVC, LinearSVC
from sklearn.linear_model import SGDClassifier
def datos(n, d=20, seed=0):
r = np.random.default_rng(seed)
X = r.normal(size=(n, d))
y = np.where(X[:, 0] + 0.5 * X[:, 1] + r.normal(size=n) > 0, 1, -1) # clases muy solapadas
return X, y
def tiempo(modelo, X, y, rep):
if rep > 1:
modelo.fit(X, y) # calentamiento de los rápidos
t = time.perf_counter()
for _ in range(rep):
modelo.fit(X, y)
return (time.perf_counter() - t) / rep
res = []
print(f"{'n':>6} {'SVC lineal':>11} {'LinearSVC':>10} {'SGD':>8} soportes de SVC")
for n in [500, 1000, 2000, 4000]:
X, y = datos(n)
s = SVC(kernel="linear", C=1.0)
ts = tiempo(s, X, y, 1)
tl = tiempo(LinearSVC(C=1.0, loss="hinge", max_iter=10_000), X, y, 3)
tg = tiempo(SGDClassifier(loss="hinge", alpha=1 / n, random_state=0), X, y, 3)
res.append((n, ts, tl, tg))
print(f"{n:6d} {ts:11.3f} {tl:10.4f} {tg:8.4f} {s.n_support_.sum()}")
r = np.array(res)
for col, nombre in [(1, "SVC lineal"), (2, "LinearSVC"), (3, "SGDClassifier")]:
k = np.polyfit(np.log(r[:, 0]), np.log(r[:, col]), 1)[0]
print(f"{nombre:14s}: tiempo ∝ n^{k:.2f}")With highly overlapping classes, over half the examples become supports and the dual becomes expensive: SVC time grows with empirical exponent near 1.8, while LinearSVC and SGDClassifier grow roughly linearly (absolute times depend on the machine and exponents vary by a few tenths between runs, but separation between groups remains). Platt measured the same at another scale: on adult (32,562 examples, linear SVM), SMO time grew as and chunking as , and with 11,221 examples SMO took 17 s versus over 20,000 s.
Common mistakes
from sklearn.svm import SVC
print("rango de las variables sin escalar:", Xtr0.min(), "a", Xtr0.max())
for nombre, A, B in [("sin escalar", Xtr0, Xte0), ("estandarizado", Xtr, Xte)]:
m = SVC(kernel="linear", C=1.0).fit(A, ytr)
print(f"SVC lineal, {nombre:13s}: {int(m.n_iter_[0]):>9,d} pasos de SMO, {m.n_support_.sum():3d} soportes, acierto {m.score(B, yte):.4f}")Exercises
SVC(kernel='linear', C=0.5) with examples and want to pose the same problem (except for treatment of ) with SGDClassifier(loss='hinge', alpha=λ), whose objective is . What should you use?More than one answer may be correct.
LinearSVC) moves one. Why?Step 1 of 4. Where do you look for the point of nearest to ?
Step 1 of 4. What does minimizing over give?
Step 1 of 4. Fix . What is optimal ?
paso_smo(a, i, j, y, K, C), returning a copy of a with a[i] and a[j] analytically optimized over the feasible segment: compute errors with K @ (a * y) (the intercept cancels in ), curvature (assume ), endpoints and depending on whether , the unbounded optimum of , its clipping and the new . All other entries stay unchanged.import numpy as np
def paso_smo(a, i, j, y, K, C):
"""Optimiza a[i] y a[j] sobre su segmento factible y devuelve una copia de a."""
a = np.array(a, dtype=float)
# tu código: E_i, E_j, eta, L, H, óptimo sin caja, recorte y nuevo a[i]
return aSummary
- With canonical normalization, margin is and maximizing it is QP with , uniquely solved for separable data.
- Soft margin adds slacks costing and equals hinge loss plus a ridge penalty with : large means weak regularization.
- The dual is with and . By complementary slackness, outside the corridor, on the edge (giving ), and for margin violators.
- SMO optimizes two at a time along the constant line, with an analytical step clipped to ; choosing the maximum-violation pair (or LIBSVM’s second-order variant) and stopping when makes it converge in few steps.
- Pegasos solves the primal with stochastic subgradient and step , in steps independent of ;
SGDClassifier(loss="hinge")is its library version. - Gap is a guaranteed stopping criterion; scale features, choose by cross-validation, and do not read as a probability in practice.