Module contents
Lesson 12 of 24Core 110 min

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 ∥w∥\norm{\vb{w}} 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 γ\gamma away from every example, any new example within γ\gamma 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 ∥δ∥∞≤ε\norm{\vb{\delta}}_\infty \le \eps changes the score by at most ε∥w∥1\eps\norm{\vb{w}}_1.
  • 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.

InteractiveThe widest corridor
2/‖w‖ = 1.91α = 0.55α = 0.30α = 0.25
  • class +1+1
  • class −1-1
  • boundary w⊤x+b=0\vb{w}\T\vb{x} + b = 0
  • edges w⊤x+b=±1\vb{w}\T\vb{x} + b = \pm 1
w\vb{w}, bb(0.795, 0.682), −0.932
Margin 1/∥w∥1/\norm{\vb{w}}0.954
Margin width 2/∥w∥2/\norm{\vb{w}}1.909
Support vectors3 of 10
∑iαi\sum_i \alpha_i and ∥w∥2\norm{\vb{w}}^21.098 and 1.098
The 3 ringed points are support vectors: only they determine the boundary. Try moving another point.
Ten draggable points from two classes. At each position the maximum-margin SVM is solved and the boundary w⊤x+b=0\vb{w}\T\vb{x} + b = 0, corridor edges w⊤x+b=±1\vb{w}\T\vb{x} + b = \pm 1, and support vectors marked with a ring and their multiplier αi\alpha_i are drawn. Move an unringed point far from the corridor: the rotation reading stays at 0°0°. Bring it into the corridor: it becomes a support and the boundary rotates. Also compare ∑iαi\sum_i \alpha_i with ∥w∥2\norm{\vb{w}}^2 in the readings. Finally, move a point across: what happens when no separating line remains?

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: ∑iαi=∥w∥2\sum_i \alpha_i = \norm{\vb{w}}^2. It follows from the KKT conditions.

Hard margin: a quadratic program

Functional and geometric margins

Let H={x:w⊤x+b=0}H = \{\vb{x} : \vb{w}\T\vb{x} + b = 0\} with w≠0\vb{w} \neq \vb{0}. Vector w\vb{w} is normal to HH and the distance from point x0\vb{x}_0 to HH is

dist⁡(x0,H)=∣w⊤x0+b∣∥w∥.\operatorname{dist}(\vb{x}_0, H) = \frac{\abs{\vb{w}\T\vb{x}_0 + b}}{\norm{\vb{w}}}.

You will prove this in the first guided exercise; it is the orthogonal projection of x0\vb{x}_0 onto HH. If (w,b)(\vb{w}, b) correctly classifies xi\vb{x}_i, the absolute value is yi(w⊤xi+b)y_i(\vb{w}\T\vb{x}_i + b), giving two measures of a classifier’s margin on the data:

  • the functional margin γ^(w,b)=min⁡iyi(w⊤xi+b)\hat\gamma(\vb{w}, b) = \min_i y_i(\vb{w}\T\vb{x}_i + b), which depends on scale: multiplying (w,b)(\vb{w}, b) by 10 multiplies it by 10 without moving the boundary;
  • the geometric margin γ(w,b)=γ^(w,b)/∥w∥\gamma(\vb{w}, b) = \hat\gamma(\vb{w}, b)/\norm{\vb{w}}, the signed distance from the closest example to the boundary, which is scale invariant: γ(cw,cb)=γ(w,b)\gamma(c\vb{w}, cb) = \gamma(\vb{w}, b) for c>0c > 0.

Scale invariance is key. Since (w,b)(\vb{w}, b) and (cw,cb)(c\vb{w}, cb) are the same classifier, we can choose any scale. Canonical normalization chooses cc so that γ^=1\hat\gamma = 1: the nearest points satisfy yi(w⊤xi+b)=1y_i(\vb{w}\T\vb{x}_i + b) = 1 and lie on hyperplanes w⊤x+b=±1\vb{w}\T\vb{x} + b = \pm 1. With that normalization the geometric margin is 1/∥w∥1/\norm{\vb{w}} and total corridor width 2/∥w∥2/\norm{\vb{w}}.

The equivalence deserves a line. If (w,b)(\vb{w}, b) is feasible for the program, its geometric margin is at least 1/∥w∥1/\norm{\vb{w}}. Conversely, any separator with γ^>0\hat\gamma > 0 rescales to (w,b)/γ^(\vb{w}, b)/\hat\gamma, which is feasible and has 1/∥w/γ^∥=γ(w,b)1/\norm{\vb{w}/\hat\gamma} = \gamma(\vb{w}, b). Thus maximizing γ\gamma means minimizing ∥w∥\norm{\vb{w}} among feasible solutions, and at the optimum some constraint is active (otherwise you could shrink (w,b)(\vb{w}, b) and reduce its norm). Squaring and multiplying by 12\tfrac12 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 x+\vb{x}_+ is an example of class +1+1 and x−\vb{x}_- one of class −1-1, their constraints give 1−w⊤x+≤b≤−1−w⊤x−1 - \vb{w}\T\vb{x}_+ \le b \le -1 - \vb{w}\T\vb{x}_-, so on the feasible subset with ∥w∥≤R\norm{\vb{w}} \le R, bb is also bounded. That subset is compact and nonempty for large RR, and 12∥w∥2\tfrac12\norm{\vb{w}}^2 is continuous: it attains its minimum.

Uniqueness of w⋆\vb{w}^\star. If (w1,b1)(\vb{w}_1, b_1) and (w2,b2)(\vb{w}_2, b_2) are optimal with w1≠w2\vb{w}_1 \neq \vb{w}_2, their midpoint is feasible (the set is convex) and, by strict convexity of ∥⋅∥2\norm{\cdot}^2, ∥12(w1+w2)∥2<12∥w1∥2+12∥w2∥2=∥w1∥2\norm{\tfrac12(\vb{w}_1 + \vb{w}_2)}^2 < \tfrac12\norm{\vb{w}_1}^2 + \tfrac12\norm{\vb{w}_2}^2 = \norm{\vb{w}_1}^2. Contradiction.

Uniqueness of b⋆b^\star. Fixing w⋆\vb{w}^\star, feasible bb form interval [ℓ,u][\ell, u] with ℓ=max⁡yi=+1(1−w⋆⊤xi)\ell = \max_{y_i = +1}(1 - \vb{w}^{\star\top}\vb{x}_i) and u=min⁡yi=−1(−1−w⋆⊤xi)u = \min_{y_i = -1}(-1 - \vb{w}^{\star\top}\vb{x}_i). If ℓ<u\ell < u, with b=(ℓ+u)/2b = (\ell + u)/2 all constraints hold with slack δ=(u−ℓ)/2>0\delta = (u - \ell)/2 > 0: yi(w⋆⊤xi+b)≥1+δy_i(\vb{w}^{\star\top}\vb{x}_i + b) \ge 1 + \delta. Then (w⋆,b)/(1+δ)(\vb{w}^\star, b)/(1 + \delta) is feasible and has smaller norm. Contradiction, hence ℓ=u\ell = u.

∎

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 CC, which, as we shall see, is the hard margin.

[ ]Hard margin as a quadratic programBrowser
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 w=(0.7955,0.6818)\vb{w} = (0.7955, 0.6818) and b=−0.9318b = -0.9318, with margin 0.95450.9545 and corridor width 1.9091.909. There are exactly three active constraints, points 0, 5 and 6 (zero-indexed), the three supports of SVC, and their multipliers sum to 1.0976=∥w∥21.0976 = \norm{\vb{w}}^2. 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 (w,b)(\vb{w}, b) 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 ξi=0\xi_i = 0 the example is outside the corridor or on its edge. With 0<ξi<10 < \xi_i < 1 it is inside the corridor but on its side of the boundary (ξi=1\xi_i = 1 means exactly on it). With ξi>1\xi_i > 1 it is misclassified. If ξi>0\xi_i > 0, the distance from the example to its corridor edge is ξi/∥w∥\xi_i/\norm{\vb{w}}, so ∑iξi\sum_i \xi_i bounds the number of training errors: each error contributes more than 1. Parameter CC sets the exchange between the two currencies, corridor width and violations.

Given (w,b)(\vb{w}, b), optimal slack is the smallest compatible with both constraints, ξi=max⁡(0,1−yif(xi))\xi_i = \max(0, 1 - y_i f(\vb{x}_i)): 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 CC: it is inverse regularization strength, C=1/(nλ)C = 1/(n\lambda). Large CC means weak regularization; small CC, strong. Intercept bb is not penalized.

InteractiveThe role of C
  • class +1+1 / −1-1 (pale: α=0\alpha = 0)
  • free support vector (0<α<C0 < \alpha < C)
  • support vector at bound (α=C\alpha = C), dashed ring
  • 0<ξ≤10 < \xi \le 1: inside margin
  • ξ>1\xi > 1: misclassified
0.00 (C = 1.00)
Width 2/∥w∥2/\norm{\vb{w}}0.956
α=0\alpha = 0 / free / α=C\alpha = C27 / 3 / 10
∑iξi\sum_i \xi_i and training errors7.21 and 2
Objective 12∥w∥2+C∑iξi\tfrac12\norm{\vb{w}}^2 + C\sum_i\xi_i9.401
Equivalent λ=1/(nC)\lambda = 1/(nC)0.0250
There are 8 points inside the margin on the correct side (amber) and 2 misclassified (purple); all have α=C\alpha = C.
Forty nonseparable points from an explicit model: x∣y=+1∼N((0.9,0.7),0.81 I)\vb{x} \given y = +1 \sim \Normal((0.9, 0.7), 0.81\,\mat{I}) and x∣y=−1∼N((−0.9,−0.5),0.81 I)\vb{x} \given y = -1 \sim \Normal((-0.9, -0.5), 0.81\,\mat{I}), twenty per class (the same as the next cell). Move CC on a logarithmic scale. Rings mark supports: solid if 0<αi<C0 < \alpha_i < C, dashed if αi=C\alpha_i = C. Each segment joins a point to its corridor edge and measures ξi/∥w∥\xi_i/\norm{\vb{w}}: amber if inside the corridor but on its own side, violet if misclassified. At right, the entire path: number of supports and corridor width versus log⁡10C\log_{10}C. What do points with segments have in common? What happens to the boundary from C≈400C \approx 400 onward?
[ ]The C pathBrowser
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 C=0.01C = 0.01 the corridor measures 5.755.75 and 38 of 40 points are supports, all at the bound: the ∥w∥2\norm{\vb{w}}^2 penalty dominates and the model barely looks at data. As CC 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 C=1000C = 1000 the corridor measures 0.0930.093: 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 C=400C = 400 and C=1000C = 1000, SVC returns the same (w,b)(\vb{w}, b), exactly the minimizer of ∑iξi\sum_i\xi_i alone, which the cell computes as a linear program. This is no coincidence. When the minimizer v0=(w0,b0)\vb{v}_0 = (\vb{w}_0, b_0) of the hinge sum hh is unique, as here, hh grows at least linearly away from it: h(v)≥h(v0)+κ∥v−v0∥h(\vb{v}) \ge h(\vb{v}_0) + \kappa\norm{\vb{v} - \vb{v}_0} for some κ>0\kappa > 0 (piecewise-linear convex functions with a unique minimum have a “sharp” minimum). And 12∥w∥2≥12∥w0∥2−∥w0∥∥w−w0∥\tfrac12\norm{\vb{w}}^2 \ge \tfrac12\norm{\vb{w}_0}^2 - \norm{\vb{w}_0}\norm{\vb{w} - \vb{w}_0}. Adding these, for C>∥w0∥/κC > \norm{\vb{w}_0}/\kappa the objective 12∥w∥2+Ch(v)\tfrac12\norm{\vb{w}}^2 + Ch(\vb{v}) is strictly greater than at v0\vb{v}_0 for any v≠v0\vb{v} \neq \vb{v}_0: beyond a finite CC the solution no longer changes. Which CC 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 d+1d + 1 variables and nn constraints. Its dual swaps roles and, above all, reveals solution structure. With multiplier αi≥0\alpha_i \ge 0 per constraint, the hard-margin Lagrangian is

L(w,b,α)=12∥w∥2−∑i=1nαi[yi(w⊤xi+b)−1].\mathcal{L}(\vb{w}, b, \vb{\alpha}) = \tfrac12\norm{\vb{w}}^2 - \sum_{i=1}^n \alpha_i\big[y_i(\vb{w}\T\vb{x}_i + b) - 1\big].

The dual function is g(α)=inf⁡w,bLg(\vb{\alpha}) = \inf_{\vb{w}, b}\mathcal{L}. For each α\vb{\alpha}, L\mathcal{L} is a convex quadratic in w\vb{w} plus a linear term in bb:

  • In w\vb{w}: ∇wL=w−∑iαiyixi=0\grad_{\vb{w}}\mathcal{L} = \vb{w} - \sum_i \alpha_i y_i\vb{x}_i = \vb{0}, hence w=∑iαiyixi\vb{w} = \sum_i \alpha_i y_i \vb{x}_i.
  • In bb: the coefficient of bb is −∑iαiyi-\sum_i \alpha_i y_i. If nonzero, the infimum is −∞-\infty (take bb to ±∞\pm\infty), so the dual is useful only where ∑iαiyi=0\sum_i \alpha_i y_i = 0.

Substituting w\vb{w} and using ∑iαiyi=0\sum_i \alpha_i y_i = 0, the term in bb disappears and

g(α)=12∥w∥2−w⊤w+∑iαi=∑i=1nαi−12∑i=1n∑j=1nαiαjyiyj xi⊤xj.g(\vb{\alpha}) = \tfrac12\norm{\vb{w}}^2 - \vb{w}\T\vb{w} + \sum_i\alpha_i = \sum_{i=1}^n \alpha_i - \frac12\sum_{i=1}^n\sum_{j=1}^n \alpha_i\alpha_j y_i y_j\, \vb{x}_i\T\vb{x}_j.

The soft-margin dual

This is the SVM dual problem. Compared with hard margin, the only addition is the upper bound αi≤C\alpha_i \le C, arising from slacks; the complete derivation is the second guided exercise. In matrix notation, with Qij=yiyjxi⊤xj\mat{Q}_{ij} = y_i y_j \vb{x}_i\T\vb{x}_j, the dual is max⁡ 1⊤α−12α⊤Qα\max\ \vb{1}\T\vb{\alpha} - \frac12\vb{\alpha}\T\mat{Q}\vb{\alpha} over the intersection of a box [0,C]n[0, C]^n with a hyperplane: a QP with nn variables, concave because Q=ZZ⊤\mat{Q} = \mat{Z}\mat{Z}\T with rows zi=yixi\vb{z}_i = y_i\vb{x}_i 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 ξi\xi_i), and for such problems the refined Slater condition requires only feasibility (strong duality). Consequently KKT conditions are necessary and sufficient: feasible α\vb{\alpha} is optimal if and only if some bb exists that, together with w=∑iαiyixi\vb{w} = \sum_i\alpha_i y_i\vb{x}_i and slacks ξi=max⁡(0,1−yif(xi))\xi_i = \max(0, 1 - y_i f(\vb{x}_i)), satisfies them.

Complementary slackness and support vectors

The soft-margin KKT conditions, with multipliers αi\alpha_i for margin constraints and μi\mu_i for ξi≥0\xi_i \ge 0, are:

  1. Stationarity: w=∑iαiyixi\vb{w} = \sum_i \alpha_i y_i\vb{x}_i,  ∑iαiyi=0\ \sum_i \alpha_i y_i = 0,  αi+μi=C\ \alpha_i + \mu_i = C.
  2. Feasibility: yif(xi)≥1−ξiy_i f(\vb{x}_i) \ge 1 - \xi_i,  ξi≥0\ \xi_i \ge 0,  αi≥0\ \alpha_i \ge 0,  μi≥0\ \mu_i \ge 0.
  3. Complementary slackness: αi[yif(xi)−1+ξi]=0\alpha_i\big[y_i f(\vb{x}_i) - 1 + \xi_i\big] = 0 and μiξi=(C−αi)ξi=0\mu_i\xi_i = (C - \alpha_i)\xi_i = 0.

Complementary slackness divides examples into three groups by αi\alpha_i, and this classification is the lesson’s central result.

αi\alpha_iKKT implicationExample locationName
αi=0\alpha_i = 0μi=C>0⇒ξi=0\mu_i = C > 0 \Rightarrow \xi_i = 0, hence yif(xi)≥1y_i f(\vb{x}_i) \ge 1outside corridor or on edgenot a support
0<αi<C0 < \alpha_i < Cμi>0⇒ξi=0\mu_i > 0 \Rightarrow \xi_i = 0, and αi>0⇒yif(xi)=1\alpha_i > 0 \Rightarrow y_i f(\vb{x}_i) = 1exactly on edgefree support
αi=C\alpha_i = Cαi>0⇒yif(xi)=1−ξi≤1\alpha_i > 0 \Rightarrow y_i f(\vb{x}_i) = 1 - \xi_i \le 1on edge, inside corridor or misclassifiedbound support

The last claim follows directly: α⋆\vb{\alpha}^\star without that coordinate still satisfies every KKT condition of the reduced problem, which is sufficient. Read backwards, the table yields diagnostic implications: if yif(xi)>1y_i f(\vb{x}_i) > 1, then αi=0\alpha_i = 0; if yif(xi)<1y_i f(\vb{x}_i) < 1, then αi=C\alpha_i = C. What cannot be inferred is the converse of the first row: a point exactly on the edge may have any αi∈[0,C]\alpha_i \in [0, C]. This happens in degenerate configurations. The last part of the hard-margin cell constructs one: with the orange support at (1.0,1.6)(1.0, 1.6) and the lower blue one at (0.4,−1.0)(0.4, -1.0), that blue point lies exactly on the edge but has α=0\alpha = 0, and only two supports hold the boundary.

Recovering bb. Each free support satisfies yi(w⊤xi+b)=1y_i(\vb{w}\T\vb{x}_i + b) = 1, and since yi2=1y_i^2 = 1, b=yi−w⊤xib = y_i - \vb{w}\T\vb{x}_i. Exactly, they all give the same value; in floating point they are averaged. If there are no free supports (this happens with small CC: in the SMO cell you will see a case with C=0.1C = 0.1 and 14 supports, all bound), KKT only says bb lies in an interval and any point in it is optimal: bb is not unique even though w\vb{w} is. LIBSVM takes the midpoint.

Two identities. Summing complementary slackness, ∑iαiyi(w⊤xi+b)=∑iαi−∑iαiξi\sum_i \alpha_i y_i(\vb{w}\T\vb{x}_i + b) = \sum_i\alpha_i - \sum_i \alpha_i\xi_i. The left side is w⊤w+b∑iαiyi=∥w∥2\vb{w}\T\vb{w} + b\sum_i\alpha_iy_i = \norm{\vb{w}}^2, and αiξi=Cξi\alpha_i\xi_i = C\xi_i because ξi>0\xi_i > 0 forces αi=C\alpha_i = C. Therefore

∥w⋆∥2=∑iαi⋆−C∑iξi⋆.\norm{\vb{w}^\star}^2 = \sum_i \alpha_i^\star - C\sum_i \xi_i^\star.

In the hard margin all slacks are zero, leaving ∥w⋆∥2=∑iαi⋆\norm{\vb{w}^\star}^2 = \sum_i\alpha_i^\star: the first figure’s identity, confirmed by the hard-margin cell (1.09761.0976 on both sides). In the soft margin, substituting into the primal, 12∥w⋆∥2+C∑iξi⋆=∑iαi⋆−12∥w⋆∥2=D(α⋆)\tfrac12\norm{\vb{w}^\star}^2 + C\sum_i\xi_i^\star = \sum_i\alpha_i^\star - \tfrac12\norm{\vb{w}^\star}^2 = D(\vb{\alpha}^\star): strong duality checked by hand.

Hard margin is a soft-margin case. If data are separable and αduro\vb{\alpha}^{\mathrm{duro}} is the hard-margin dual solution, for every C≥max⁡iαiduroC \ge \max_i \alpha_i^{\mathrm{duro}} that same vector is feasible for the soft dual and satisfies its KKT conditions with ξ=0\xi = \vb{0}, μi=C−αi≥0\mu_i = C - \alpha_i \ge 0. Thus soft margin with sufficiently large CC is hard margin, not an approximation. That is why the corridor figure uses SMO with C=104C = 10^4 and the cell compares with SVC(C=1e6).

Hinge versus logistic: sparse solutions

Logistic regression with the same penalty, min⁡12∥w∥2+C∑ilog⁡(1+e−mi)\min \tfrac12\norm{\vb{w}}^2 + C\sum_i\log(1 + e^{-m_i}) with mi=yif(xi)m_i = y_if(\vb{x}_i), has an optimality condition of the same form as SVM. Setting the gradient in w\vb{w} to zero,

w=∑i=1nβi yixi,βi=C σ(−mi)∈(0,C).\vb{w} = \sum_{i=1}^n \beta_i\,y_i\vb{x}_i, \qquad \beta_i = C\,\sigma(-m_i) \in (0, C).

The difference is in the weights: σ(−m)\sigma(-m) is small for large margins but never zero. Hinge loss, by contrast, is exactly flat from m=1m = 1 onward and produces exactly zero weights.

InteractiveHinge versus logistic
Weight of each point in the solution, ordered by its SVM margin
C = 1
  • SVM: boundary, margin and αi\alpha_i bars
  • logistic: boundary and βi=C σ(−mi)\beta_i = C\,\sigma(-m_i) points
  • both boundaries without added points (the SVM boundary is hidden until it moves)
  • added points (orange background in weight panel)
12
1.50
SVM: rotation and shift0.00°, 0.000
Logistic regression: rotation and shift7.41°, 0.238
Largest α\alpha among added points (SVM)0.000
Sum of β\beta for added points (logistic)0.907
The 12 points have zero hinge loss: their α\alpha values are zero and the SVM does not move. Logistic regression assigns them total weight 0.91 and rotates 7.4°.
Twenty points from the same model as the previous figure, with another seed (the points in ‘SMO from scratch’), fitted with a linear SVM and logistic regression with the same penalty 12∥w∥2\tfrac12\norm{\vb{w}}^2, same C=1C = 1 and unpenalized bb. Add kk class +1+1 points in a column parallel to the boundary, with score dd under the SVM without them. At right, each point's weight in the solution: SVM αi\alpha_i (bars) and logistic βi=Cσ(−mi)\beta_i = C\sigma(-m_i) (points), ordered by their SVM margin. With d≥1d \ge 1, how far does each boundary move? Lower dd below 1: what changes in the weight panel?

With the twelve initial points at d=1.5d = 1.5, the SVM boundary does not move and the added points’ α\alpha are exactly 0, while logistic regression rotates several degrees because each added point contributes a positive βi\beta_i. The weight panel shows the full structure: SVM bars appear only on the left, at points with margin at most 1, and equal CC for those violating the margin; logistic points decrease smoothly to the right without reaching zero. As soon as dd 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 nn variables and matrix Q\mat{Q} has n2n^2 entries: with n=105n = 10^5, 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 ∑iαiyi=0\sum_i\alpha_iy_i = 0. If you change one αj\alpha_j leaving the rest fixed, αjyj\alpha_jy_j cannot change, so neither can αj\alpha_j. With two, the constraint leaves a line: αiyi+αjyj\alpha_iy_i + \alpha_jy_j 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 f0(x)=w⊤xf_0(\vb{x}) = \vb{w}\T\vb{x}, with w=∑kαkykxk\vb{w} = \sum_k\alpha_ky_k\vb{x}_k, and each example’s error as Ek=f(xk)−ykE_k = f(\vb{x}_k) - y_k. To move along the constraint line, change αj→αj+yjt\alpha_j \to \alpha_j + y_jt and αi→αi−yit\alpha_i \to \alpha_i - y_it: sum ∑kαkyk\sum_k\alpha_ky_k changes by yj2t−yi2t=0y_j^2t - y_i^2t = 0. Call that direction d\vb{d} (dj=yjd_j = y_j, di=−yid_i = -y_i, rest zero).

  • Slope. The dual gradient is ∇D=1−Qα\grad D = \vb{1} - \mat{Q}\vb{\alpha}, with (Qα)k=ykf0(xk)(\mat{Q}\vb{\alpha})_k = y_kf_0(\vb{x}_k). Then d⊤∇D=yj−f0(xj)−yi+f0(xi)=Ei−Ej\vb{d}\T\grad D = y_j - f_0(\vb{x}_j) - y_i + f_0(\vb{x}_i) = E_i - E_j. Intercept bb cancels in the subtraction.
  • Curvature. d⊤Qd=∑k,ldkdlykylxk⊤xl\vb{d}\T\mat{Q}\vb{d} = \sum_{k,l}d_kd_ly_ky_l\vb{x}_k\T\vb{x}_l with diyi=−1d_iy_i = -1 and djyj=1d_jy_j = 1, giving ∥xj−xi∥2=xi⊤xi+xj⊤xj−2xi⊤xj≕η\norm{\vb{x}_j - \vb{x}_i}^2 = \vb{x}_i\T\vb{x}_i + \vb{x}_j\T\vb{x}_j - 2\vb{x}_i\T\vb{x}_j \eqqcolon \eta.

Since DD is quadratic, it is exactly a parabola along the line:

D(α+td)=D(α)+(Ei−Ej) t−12η t2.D(\vb{\alpha} + t\vb{d}) = D(\vb{\alpha}) + (E_i - E_j)\,t - \tfrac12\eta\,t^2.

If η>0\eta > 0, its maximum is at t⋆=(Ei−Ej)/ηt^\star = (E_i - E_j)/\eta, giving Platt’s formula

αjnuevo=αj+yj(Ei−Ej)η.\alpha_j^{\text{nuevo}} = \alpha_j + \frac{y_j(E_i - E_j)}{\eta}.

The box remains. Both coordinates must stay in [0,C][0, C], restricting αj\alpha_j to interval [L,H][L, H]:

  • if yi≠yjy_i \neq y_j (the line is constant αj−αi\alpha_j - \alpha_i): L=max⁡(0,αj−αi)L = \max(0, \alpha_j - \alpha_i), H=min⁡(C,C+αj−αi)H = \min(C, C + \alpha_j - \alpha_i);
  • if yi=yjy_i = y_j (the line is constant αi+αj\alpha_i + \alpha_j): L=max⁡(0,αi+αj−C)L = \max(0, \alpha_i + \alpha_j - C), H=min⁡(C,αi+αj)H = \min(C, \alpha_i + \alpha_j).

Because the parabola is concave, its segment maximum is the clipped free maximum: αjnuevo←min⁡(max⁡(αjnuevo,L),H)\alpha_j^{\text{nuevo}} \leftarrow \min(\max(\alpha_j^{\text{nuevo}}, L), H). Then αinuevo=αi+yiyj(αj−αjnuevo)\alpha_i^{\text{nuevo}} = \alpha_i + y_iy_j(\alpha_j - \alpha_j^{\text{nuevo}}), maintaining the line. With a linear kernel, η=0\eta = 0 only if xi=xj\vb{x}_i = \vb{x}_j; then DD is linear along the line and the maximum lies at an endpoint, which Platt chooses by evaluating the objective at both.

InteractiveSMO step by step
i = 1j = 11
C = 10
Gain ΔD\Delta D along the line versus αj\alpha_j
  • D(α)
  • optimum D*
  • maximum violation
  • tolerance 10⁻³
  • selected pair (i,j)(i, j)
  • feasible segment
  • unconstrained optimum
  • final boundary
  • ring: support vector (dashed if α=C\alpha = C)
step 1 of 18
C
Pair selection
Pair (i,j)(i, j) and yiyjy_i y_j(1, 11), −1
Ei−EjE_i - E_j and η\eta−2.000 and 4.143
[L,H][L, H] for αj\alpha_j[0.000, 1.000]
αj\alpha_j: unconstrained → clipped0.483 → 0.483
αi\alpha_i and αj\alpha_j becomefree and free
Dual gain ΔD\Delta D0.4827
KKT violation before the step2.0000
The parabola optimum lies inside the segment: the step is exact and no clipping is needed.
SMO on the twenty ‘Hinge versus logistic’ points, with LIBSVM tolerance 10−310^{-3}. At left, the current boundary and pair (i,j)(i, j) in violet; rings show current supports. Upper right, the (αi,αj)(\alpha_i, \alpha_j) plane: box [0,C]2[0, C]^2, constraint line, feasible segment between LL and HH (violet), starting point (gray outline), unconstrained optimum (red outline) and clipped point. Below, parabola ΔD\Delta D along the line with forbidden regions shaded. At the bottom, dual objective and maximum KKT violation per step. Step through and find a step where the free optimum leaves the box. Then switch to ‘Random’ with the same CC: how many steps now? Try C=0.1C = 0.1: how many free supports remain?

Which pair to choose

Any pair with η>0\eta > 0 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 ii, a second maximizing ∣Ei−Ej∣\abs{E_i - E_j}, a cheap approximation to step size. KKT conditions are checked with a tolerance; Platt writes that it is “typically” 10−310^{-3} and that an output between 0.9990.999 and 1.0011.001 at a boundary point is acceptable for recognition.

The rule used today by LIBSVM and scikit-learn follows from rewriting KKT. Call st=yt−f0(xt)s_t = y_t - f_0(\vb{x}_t) the value of bb that would put example tt exactly on its edge. Reviewing the table’s three cases for each class, KKT says b≥stb \ge s_t for the tt in

Iup={t:yt=+1,αt<C}∪{t:yt=−1,αt>0},I_{\text{up}} = \{t : y_t = +1, \alpha_t < C\} \cup \{t : y_t = -1, \alpha_t > 0\},

and b≤stb \le s_t for those in Ilow={t:yt=+1,αt>0}∪{t:yt=−1,αt<C}I_{\text{low}} = \{t : y_t = +1, \alpha_t > 0\} \cup \{t : y_t = -1, \alpha_t < C\}. Such an bb exists if and only if

m(α)=max⁡t∈Iupst ≤ min⁡t∈Ilowst=M(α).m(\vb{\alpha}) = \max_{t \in I_{\text{up}}} s_t \ \le\ \min_{t \in I_{\text{low}}} s_t = M(\vb{\alpha}).

The difference m(α)−M(α)m(\vb{\alpha}) - M(\vb{\alpha}) is the maximum KKT violation, and its pair i=arg max⁡Iupsti = \argmax_{I_{\text{up}}} s_t, j=arg min⁡Ilowstj = \argmin_{I_{\text{low}}} s_t is Keerthi et al.’s (2001) maximum-violation pair. For that pair, slope Ei−EjE_i - E_j of the parabola equals exactly −(m−M)-(m - M) (remember Et=−st+bE_t = -s_t + b): choosing it selects, among all two-coordinate directions respecting constraints, the steepest ascent direction, and the natural stopping criterion is m(α)−M(α)<τm(\vb{\alpha}) - M(\vb{\alpha}) < \tau. Keerthi and Gilbert (2002) proved that with this rule SMO terminates in finitely many steps for any τ>0\tau > 0. LIBSVM uses a second-order version (Fan, Chen and Lin, 2005): it takes the same ii, but chooses jj by the gain from the unclipped step, (si−sj)2/(2ηij)(s_i - s_j)^2/(2\eta_{ij}), accounting for curvature as well as slope. Its default tolerance is τ=10−3\tau = 10^{-3}, the tol of SVC.

At the optimum, m≤Mm \le M and bb may be any point of [m,M][m, M]; in practice the mean of free-support sts_t is used if any exist, otherwise midpoint (m+M)/2(m + M)/2.

SMO from scratch

[ ]SMO from scratchBrowser
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 C=1C = 1, SMO using maximum violation converges in 18 steps with 11 supports (3 free and 8 bound), the same as SVC; w\vb{w} and bb differ from SVC in the third decimal, expected given tolerance 10−310^{-3} and two different selection rules. With C=0.1C = 0.1 all supports are bound and bb comes from the interval midpoint, yet agrees with SVC, which uses the same rule. With C=10C = 10 it takes 118 steps: large CC makes the box wider and α\alpha 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.

[ ]SMO on breast_cancerBrowser
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 C=1C = 1 it takes 2203 steps and matches SVC: 27 supports, the same dual objective to five decimals, bb equal to three decimals, and cosine 1.0000001.000000 between the two w\vb{w}. The last part shows why the function snaps α\alpha to the exact bound. Without doing so, subtraction αi+yiyj(αj−αjnuevo)\alpha_i + y_iy_j(\alpha_j - \alpha_j^{\text{nuevo}}) leaves αi=5.2×10−18\alpha_i = 5.2\times 10^{-18} instead of 0 due to rounding; that example, which should be at the bound, still counts as “αt>0\alpha_t > 0” and enters the set of those able to decrease α\alpha; the rule chooses it repeatedly, but the step would require αt<0\alpha_t < 0 and clipping leaves it unchanged; SMO gets stuck with violation 3.23.2 and objective 3.923.92 versus 14.2014.20. 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 m−Mm - M is convenient, but how far is the objective really from optimal? Weak duality gives a guaranteed answer: for any feasible α\vb{\alpha} and any (w,b)(\vb{w}, b), P(w,b)≥D(α)P(\vb{w}, b) \ge D(\vb{\alpha}), and they are equal at the optimum. Thus P−DP - D bounds both the dual’s shortfall and the primal’s excess. During SMO, current w=∑iαiyixi\vb{w} = \sum_i\alpha_iy_i\vb{x}_i gives a primal, and it is useful to choose the best bb for that w\vb{w}: min⁡b∑imax⁡(0,1−yi(f0(xi)+b))\min_b \sum_i\max(0, 1 - y_i(f_0(\vb{x}_i) + b)) is convex and piecewise linear in bb, so its minimum lies at one of the breakpoints b=yi−f0(xi)b = y_i - f_0(\vb{x}_i).

[ ]Duality gap and KKT during SMOBrowser
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 ff units (“no point is more than τ\tau away from satisfying KKT”), while relative gap measures objective shortfall. In this run, the first time violation falls below 10−310^{-3} (LIBSVM’s default criterion) the relative gap is already of order 10−410^{-4}: the standard criterion solves the objective to four digits. Pointwise checking of the final solution reproduces the complementary-slackness table: the 371 points with α=0\alpha = 0 have yf(x)≥1.016y f(\vb{x}) \ge 1.016, the 16 free ones are on the edge with error below 10−610^{-6} and the 11 bound ones have yf(x)≤0.985y f(\vb{x}) \le 0.985.

Pegasos: stochastic subgradient on the primal

SMO needs the nn errors EkE_k in memory, and updating them each step costs O(n)\bigO(n) kernel evaluations. When nn 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,

F(w)=λ2∥w∥2+1n∑i=1nmax⁡(0,1−yiw⊤xi),F(\vb{w}) = \frac{\lambda}{2}\norm{\vb{w}}^2 + \frac1n\sum_{i=1}^n \max\big(0, 1 - y_i\vb{w}\T\vb{x}_i\big),

is not differentiable where yiw⊤xi=1y_i\vb{w}\T\vb{x}_i = 1, but is convex and λ\lambda-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 tt:

  1. Choose iti_t randomly from 1,…,n1, \dots, n and take ηt=1/(λt)\eta_t = 1/(\lambda t).
  2. A subgradient of the objective at that example is λwt−1[yitwt⊤xit<1] yitxit\lambda\vb{w}_t - \ind[y_{i_t}\vb{w}_t\T\vb{x}_{i_t} < 1]\,y_{i_t}\vb{x}_{i_t}, so
wt+1=(1−ηtλ) wt+ηt 1[yitwt⊤xit<1] yitxit.\vb{w}_{t+1} = (1 - \eta_t\lambda)\,\vb{w}_t + \eta_t\,\ind[y_{i_t}\vb{w}_t\T\vb{x}_{i_t} < 1]\,y_{i_t}\vb{x}_{i_t}.
  1. (Optional) Project onto the ball of radius 1/λ1/\sqrt{\lambda}: wt+1←min⁡(1,1/λ∥wt+1∥)wt+1\vb{w}_{t+1} \leftarrow \min\big(1, \frac{1/\sqrt\lambda}{\norm{\vb{w}_{t+1}}}\big)\vb{w}_{t+1}.

With ηt=1/(λt)\eta_t = 1/(\lambda t), factor 1−ηtλ=1−1/t1 - \eta_t\lambda = 1 - 1/t turns the recursion into an average. By induction,

wt+1=1λt∑s=1t1[yisws⊤xis<1] yisxis:\vb{w}_{t+1} = \frac{1}{\lambda t}\sum_{s=1}^{t}\ind[y_{i_s}\vb{w}_s\T\vb{x}_{i_s} < 1]\,y_{i_s}\vb{x}_{i_s}:

the iterate is a scaled sum of examples that violated the margin when selected. It has the same form ∑iβiyixi\sum_i \beta_iy_i\vb{x}_i as the dual, so Pegasos also supports kernels.

Projection does not change the optimum, because ∥w⋆∥≤1/λ\norm{\vb{w}^\star} \le 1/\sqrt\lambda. On this form’s scale, the previous section’s dual is written with w⋆=1λn∑iαiyixi\vb{w}^\star = \frac{1}{\lambda n}\sum_i\alpha_iy_i\vb{x}_i and αi∈[0,1]\alpha_i \in [0, 1], and strong duality gives λ∥w⋆∥2=1n∑iαi−1n∑imax⁡(0,1−yiw⋆⊤xi)≤1\lambda\norm{\vb{w}^\star}^2 = \frac1n\sum_i\alpha_i - \frac1n\sum_i\max(0, 1 - y_i\vb{w}^{\star\top}\vb{x}_i) \le 1.

What it guarantees. The paper’s main result is that the number of steps to precision ε\eps is O~(1/(λε))\tilde{\bigO}(1/(\lambda\eps)), versus Ω(1/ε2)\Omega(1/\eps^2) from earlier stochastic-gradient analyses for SVM; with sparse data having dd nonzero entries per example, total time is O~(d/(λε))\tilde{\bigO}(d/(\lambda\eps)) and does not depend on nn. Specifically (corollary 2), with probability at least 1−δ1 - \delta the mean iterate satisfies F(wˉ)−F(w⋆)≤21 cln⁡(T/δ)/(λT)F(\bar{\vb{w}}) - F(\vb{w}^\star) \le 21\,c\ln(T/\delta)/(\lambda T), with c=4R2c = 4R^2 without projection and R≥max⁡i∥xi∥R \ge \max_i\norm{\vb{x}_i}. This is SGD’s O(log⁡T/(λT))\bigO(\log T/(\lambda T)) 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 bb. Section 6 discusses three ways to add it: as a constant feature equal to 1 (simple, but then b2b^2 is penalized and it is a different problem), in the loss without penalizing it (the objective ceases to be strongly convex in bb and the guarantee drops to O(1/T)\bigO(1/\sqrt{T})), or with an outer search loop over bb. The first is what LIBLINEAR uses (LinearSVC, with its intercept_scaling) and what we use here.

InteractivePegasos: subgradient with step 1/(λt)
  • last iterate
  • average iterate
  • slope −1
  • exact optimum
  • last iterate vt\vb{v}_t
  • average vˉt\bar{\vb{v}}_t
  • class +1+1
  • class −1-1
t = 20 000
−1.60
Step tt and ηt=1/(λt)\eta_t = 1/(\lambda t)20 000, 0.0020
(F−F⋆)/F⋆(F - F^\star)/F^\star: last and average0.0049 and 0.0046
λ\lambda, CC and F⋆F^\star0.0250, 1.00, 0.23507
∥vt∥\norm{\vb{v}_t} and radius 1/λ1/\sqrt{\lambda}2.102 and 6.325
With λ=0.0250\lambda = 0.0250 (equivalent to C=1.00C = 1.00 with n=40n = 40), the initial step η1=40.0\eta_1 = 40.0 is enormous and decreases as 1/t1/t. Smaller λ\lambda takes longer: theory gives O~(1/(λε))\tilde O(1/(\lambda\varepsilon)) steps.
Pegasos on the forty points from ‘The role of C’, with bb as a third constant feature. The exact optimum of the same objective (dashed line) is computed by coordinate descent on the dual, LIBLINEAR's method. Play: time advances on a logarithmic scale to T=20 000T = 20\,000 steps. At left, the last iterate's boundary and the mean iterate's; at right, each one's relative excess (F−F⋆)/F⋆(F - F^\star)/F^\star on a log-log scale, with a slope −1-1 guide through the mean at t=100t = 100. Which curve arrives sooner? Lower λ\lambda (increase CC): what happens to speed? Change seed and enable projection.

In the figure, the first steps are violent: with λ=0.025\lambda = 0.025, η1=40\eta_1 = 40 and the first iterate is 40 yi1xi140\,y_{i_1}\vb{x}_{i_1}, 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 −1-1, the 1/t1/t rate, with much more noise for the last iterate. Lowering λ\lambda shifts the curves up: more time is needed, as the bound says.

[ ]Pegasos from scratchBrowser
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 λ=1/(398⋅1)=0.00251\lambda = 1/(398 \cdot 1) = 0.00251, the last iterate’s relative excess falls from 5.65.6 to 0.210.21 and 0.0260.026 across 10310^3, 10410^4 and 10510^5 steps: a factor 26 in the first decade, still carrying the initial phase, and a factor 8 in the second, already close to the 1/T1/T rate. The mean trails (2727, 1.51.5 and 0.0910.091), as in the figure and as the authors observed, and projection barely changes the end. In test accuracy Pegasos already matches LinearSVC after 10410^4 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 ηt=1/(α(t+t0))\eta_t = 1/(\alpha(t + t_0)) with Bottou’s heuristic t0t_0, and its alpha is our λ\lambda (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 0.0040.004 and an (w,b)(\vb{w}, b) differing from LinearSVC by less than 0.030.03 in each component.

Multiclass and probabilities

SVM is binary. For KK classes there are two standard constructions:

  • One versus rest (OvR): KK classifiers, the kk-th trained on class kk versus all others, predicting arg max⁡kfk(x)\argmax_k f_k(\vb{x}). Scores from different classifiers do not share a scale, so arg max⁡\argmax is a heuristic. This is what LinearSVC does.
  • One versus one (OvO): K(K−1)/2K(K - 1)/2 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 nn, it is often cheaper. SVC always does this: its decision_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 P(Y=1∣x)−1/2P(Y = 1 \given \vb{x}) - 1/2, 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 σ(af+c)\sigma(af + c). SVC(probability=True) did this with internal five-fold cross-validation, and since scikit-learn 1.9 is deprecated in favor of CalibratedClassifierCV.

[ ]Multiclass and probabilitiesBrowser
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 98.5 %98.5\,\% and OvR (10 classifiers) 96.7 %96.7\,\%; LinearSVC, also OvR, reaches 96.9 %96.9\,\%. 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

ClassLibrary and algorithmLoss and interceptWhen
SVC(kernel="linear")LIBSVM: SMO with second-order selection, kernel cachehinge; unpenalized bbnn up to tens of thousands; need α\alpha or will use kernels
LinearSVCLIBLINEAR: dual coordinate descent (Hsieh et al., 2008) or primal Newtonsquared hinge by default; bb as penalized featurelinear model with large nn or sparse data
SGDClassifier(loss="hinge")SGD with ηt=1/(α(t+t0))\eta_t = 1/(\alpha(t + t_0))hinge; unpenalized bbhuge nn, 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 α\alpha at a time precisely because treating bb as another feature removes constraint ∑iαiyi=0\sum_i\alpha_iy_i = 0 from the dual: it is SMO without the reason for pairs. Third, SVC solves the dual, whose cost grows at least quadratically with nn; its documentation says so and recommends the other two classes for large datasets.

Choosing C by cross-validation

CC is a hyperparameter, and its useful value depends on data scale and nn. The practical guide by Hsu, Chang and Lin, LIBSVM’s authors, recommends scaling each feature and searching CC on an exponential grid (2−5,2−3,…,2152^{-5}, 2^{-3}, \dots, 2^{15} in their example) with cross-validation. Scaling goes inside a pipeline so each fold fits it on its own training data.

[ ]C by cross-validationBrowser
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 C=2−10C = 2^{-10} the model is overregularized (93.0% and 197 supports), the maximum is at C=2−2=0.25C = 2^{-2} = 0.25 (99.25% cross-validation accuracy), and accuracy then falls slowly while support count plateaus around 24. The selected CC 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

[ ]How each solver scales with nBrowser
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 n1.9n^{1.9} and chunking as n3.1n^{3.1}, and with 11,221 examples SMO took 17 s versus over 20,000 s.

Common mistakes

[ ]To scale or not to scaleBrowser
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

NumericCorridor width
A hard-margin SVM's canonical solution is w=(3,4)\vb{w} = (3, 4), b=−2b = -2. What is the total corridor width between the two classes?
QuizWhere is a free support?
In a soft-margin SVM solution, an example has 0<αi<C0 < \alpha_i < C. Where is it?
NumericReading α from output
In a soft-margin SVM solution with C=2C = 2, an example with yi=+1y_i = +1 has f(xi)=0.25f(\vb{x}_i) = 0.25. What is αi\alpha_i?
NumericFrom C to λ
You train SVC(kernel='linear', C=0.5) with n=2000n = 2000 examples and want to pose the same problem (except for treatment of bb) with SGDClassifier(loss='hinge', alpha=λ), whose objective is 1n∑imax⁡(0,1−yif(xi))+λ2∥w∥2\frac1n\sum_i \max(0, 1 - y_if(\vb{x}_i)) + \frac{\lambda}{2}\norm{\vb{w}}^2. What λ\lambda should you use?
QuizAdding and removing examples
You have a linear SVM and logistic regression trained on the same data with the same penalty 12∥w∥2\tfrac12\norm{\vb{w}}^2 and the same CC. Which statements are true when retraining after changing the training set?

More than one answer may be correct.

NumericWhat does each multiclass strategy cost?
You have K=10K = 10 balanced classes and nn examples, and the cost of training a binary SVM on mm examples grows as m2m^2. How many times more does one versus rest cost to train than one versus one? (Give the OvR / OvO cost ratio.)
QuizWhy pairs?
SMO optimizes two multipliers each step, while LIBLINEAR coordinate descent (in LinearSVC) moves one. Why?
QuizNo free supports
You solve an SVM with small CC and all αi⋆\alpha_i^\star are 0 or CC: there are no free supports. What can you say about the solution?
ProofDistance to a hyperplane and canonical margin
Prove: The distance from x0\vb{x}_0 to hyperplane H={x:w⊤x+b=0}H = \{\vb{x} : \vb{w}\T\vb{x} + b = 0\}, with w≠0\vb{w} \neq \vb{0}, is ∣w⊤x0+b∣/∥w∥\abs{\vb{w}\T\vb{x}_0 + b}/\norm{\vb{w}}; and if (w,b)(\vb{w}, b) is in canonical form, min⁡iyi(w⊤xi+b)=1\min_i y_i(\vb{w}\T\vb{x}_i + b) = 1, geometric margin is 1/∥w∥1/\norm{\vb{w}}.
0
Let u=w/∥w∥\vb{u} = \vb{w}/\norm{\vb{w}} be the unit normal vector.

Step 1 of 4. Where do you look for the point of HH nearest to x0\vb{x}_0?

ProofThe soft-margin dual
Prove: The soft-margin SVM dual is max⁡α∑iαi−12∑i,jαiαjyiyjxi⊤xj\max_{\vb{\alpha}} \sum_i\alpha_i - \frac12\sum_{i,j}\alpha_i\alpha_jy_iy_j\vb{x}_i\T\vb{x}_j subject to 0≤αi≤C0 \le \alpha_i \le C and ∑iαiyi=0\sum_i\alpha_iy_i = 0.
0
With multipliers αi≥0\alpha_i \ge 0 for yi(w⊤xi+b)≥1−ξiy_i(\vb{w}\T\vb{x}_i + b) \ge 1 - \xi_i and μi≥0\mu_i \ge 0 for ξi≥0\xi_i \ge 0, the Lagrangian is L=12∥w∥2+C∑iξi−∑iαi[yi(w⊤xi+b)−1+ξi]−∑iμiξi\mathcal{L} = \tfrac12\norm{\vb{w}}^2 + C\sum_i\xi_i - \sum_i\alpha_i[y_i(\vb{w}\T\vb{x}_i + b) - 1 + \xi_i] - \sum_i\mu_i\xi_i. The dual function is its unconstrained infimum over (w,b,ξ)(\vb{w}, b, \vb{\xi}).

Step 1 of 4. What does minimizing over w\vb{w} give?

ProofSoft margin is regularized hinge loss
Prove: The soft-margin SVM has the same minimizers (w,b)(\vb{w}, b) as ∑imax⁡(0,1−yi(w⊤xi+b))+12C∥w∥2\sum_i\max(0, 1 - y_i(\vb{w}\T\vb{x}_i + b)) + \frac{1}{2C}\norm{\vb{w}}^2, and as mean hinge loss plus λ2∥w∥2\frac{\lambda}{2}\norm{\vb{w}}^2 with λ=1/(nC)\lambda = 1/(nC).
0
Write F(w,b,ξ)=12∥w∥2+C∑iξiF(\vb{w}, b, \vb{\xi}) = \tfrac12\norm{\vb{w}}^2 + C\sum_i\xi_i and fi=w⊤xi+bf_i = \vb{w}\T\vb{x}_i + b.

Step 1 of 4. Fix (w,b)(\vb{w}, b). What is optimal ξi\xi_i?

CodeThe analytical SMO step
Implement 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 Ek=f0(xk)−ykE_k = f_0(\vb{x}_k) - y_k with f0=f_0 = K @ (a * y) (the intercept cancels in Ei−EjE_i - E_j), curvature η=Kii+Kjj−2Kij\eta = K_{ii} + K_{jj} - 2K_{ij} (assume η>0\eta > 0), endpoints LL and HH depending on whether yi=yjy_i = y_j, the unbounded optimum of αj\alpha_j, its clipping and the new αi\alpha_i. 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 a
Shift+Enter to run

Summary

Key idea
Among separating boundaries, SVM chooses the widest corridor; its dual reveals that the solution is a combination of a few examples, the support vectors, and depends only on dot products between them.
  • With canonical normalization, margin is 1/∥w∥1/\norm{\vb{w}} and maximizing it is QP min⁡12∥w∥2\min\tfrac12\norm{\vb{w}}^2 with yi(w⊤xi+b)≥1y_i(\vb{w}\T\vb{x}_i + b) \ge 1, uniquely solved for separable data.
  • Soft margin adds slacks costing CC and equals hinge loss plus a ridge penalty with λ=1/(nC)\lambda = 1/(nC): large CC means weak regularization.
  • The dual is max⁡∑αi−12∑αiαjyiyjxi⊤xj\max\sum\alpha_i - \tfrac12\sum\alpha_i\alpha_jy_iy_j\vb{x}_i\T\vb{x}_j with 0≤αi≤C0 \le \alpha_i \le C and ∑αiyi=0\sum\alpha_iy_i = 0. By complementary slackness, αi=0\alpha_i = 0 outside the corridor, 0<αi<C0 < \alpha_i < C on the edge (giving bb), and αi=C\alpha_i = C for margin violators.
  • SMO optimizes two α\alpha at a time along the constant yiαi+yjαjy_i\alpha_i + y_j\alpha_j line, with an analytical step clipped to [L,H][L, H]; choosing the maximum-violation pair (or LIBSVM’s second-order variant) and stopping when m(α)−M(α)<10−3m(\vb{\alpha}) - M(\vb{\alpha}) < 10^{-3} makes it converge in few steps.
  • Pegasos solves the primal with stochastic subgradient and step 1/(λt)1/(\lambda t), in O~(1/(λε))\tilde{\bigO}(1/(\lambda\eps)) steps independent of nn; SGDClassifier(loss="hinge") is its library version.
  • Gap P−DP - D is a guaranteed stopping criterion; scale features, choose CC by cross-validation, and do not read f(x)f(\vb{x}) as a probability in practice.