TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Support Vector Machines: Margin and Hinge Loss

Support Vector Machines: Margin and Hinge Loss

When two classes can be separated by a line, infinitely many lines do it. Logistic regression picks the one that maximises the likelihood; a support vector machine (SVM) picks the one with the widest margin, the widest empty street between the classes. The idea, due to Vapnik and colleagues in the 1990s, gives a classifier defined by a handful of boundary points (the support vectors), a convex training problem, and, through kernels in the next lesson, nonlinear boundaries at the cost of a linear model. The Machine Learning course uses SVC; here you solve the SVM's optimisation problem yourself.

The margin

Labels are yi∈{−1,+1}y_i \in \{-1, +1\} and the classifier is f(x)=w⊤x+bf(\mathbf{x}) = \mathbf{w}^\top \mathbf{x} + b, predicting the sign. Scale w\mathbf{w} and bb so that the closest points satisfy yif(xi)=1y_i f(\mathbf{x}_i) = 1. The distance between the two lines f=+1f = +1 and f=−1f = -1 is then

margin=2∥w∥,\text{margin} = \frac{2}{\lVert \mathbf{w} \rVert},

so maximising the margin means minimising ∥w∥\lVert \mathbf{w} \rVert. Real data overlaps, so the soft-margin SVM allows violations ξi≥0\xi_i \ge 0 at a price CC:

min⁡w,b,ξ 12∥w∥2+C∑i=1nξisubject toyi(w⊤xi+b)≥1−ξi,  ξi≥0.\min_{\mathbf{w}, b, \boldsymbol{\xi}} \ \frac{1}{2} \lVert \mathbf{w} \rVert^2 + C \sum_{i=1}^{n} \xi_i \quad \text{subject to} \quad y_i (\mathbf{w}^\top \mathbf{x}_i + b) \ge 1 - \xi_i, \ \ \xi_i \ge 0 .

At the optimum ξi=max⁡(0,1−yif(xi))\xi_i = \max(0, 1 - y_i f(\mathbf{x}_i)), the hinge loss, so the problem is unconstrained regularised hinge-loss minimisation:

min⁡w,b 12∥w∥2+C∑i=1nmax⁡(0, 1−yi(w⊤xi+b))\min_{\mathbf{w}, b} \ \frac{1}{2} \lVert \mathbf{w} \rVert^2 + C \sum_{i=1}^{n} \max\big(0, \ 1 - y_i(\mathbf{w}^\top \mathbf{x}_i + b)\big)

Compare with logistic regression: same penalty, but the log-loss log⁡(1+e−yf)\log(1 + e^{-yf}) is replaced by the hinge, which is exactly zero for points beyond the margin. Those points have no influence at all, which is why the solution depends only on the support vectors. Derivations: Separating Hyperplanes and the Margin, Soft Margin and the Hinge Loss.

The dual problem

With Lagrange multipliers αi\alpha_i for the constraints, the problem turns into its dual (The Dual SVM and Kernels, Inequality Constraints and the KKT Conditions):

max⁡α ∑iαi−12∑i,jαiαjyiyj xi⊤xjsubject to0≤αi≤C,  ∑iαiyi=0,\max_{\boldsymbol{\alpha}} \ \sum_{i} \alpha_i - \frac{1}{2} \sum_{i,j} \alpha_i \alpha_j y_i y_j \, \mathbf{x}_i^\top \mathbf{x}_j \quad \text{subject to} \quad 0 \le \alpha_i \le C, \ \ \sum_i \alpha_i y_i = 0,

with w=∑iαiyixi\mathbf{w} = \sum_i \alpha_i y_i \mathbf{x}_i. The KKT conditions sort the points: αi=0\alpha_i = 0 beyond the margin (not support vectors), 0<αi<C0 < \alpha_i < C exactly on the margin (these give bb), αi=C\alpha_i = C inside the margin or misclassified. The data enters only through dot products xi⊤xj\mathbf{x}_i^\top \mathbf{x}_j, the door to kernels.

Solving the dual from scratch

A small quadratic program fits a general-purpose solver (SciPy's SLSQP) on 40 points:

python · try it yourself
import numpy as np
from scipy.optimize import minimize
from sklearn.datasets import make_blobs
from sklearn.svm import SVC

X, y01 = make_blobs(n_samples=40, centers=[[-1.5, -1], [1.5, 1]], cluster_std=1.0, random_state=0)
y = np.where(y01 == 1, 1.0, -1.0)                     # SVM labels are -1 and +1
C = 1.0

# Dual problem: maximise sum(a) - 1/2 a^T Q a  subject to 0 <= a <= C and sum(a y) = 0
Q = (y[:, None] * y[None, :]) * (X @ X.T)
res = minimize(lambda a: 0.5 * a @ Q @ a - a.sum(), np.zeros(len(y)), jac=lambda a: Q @ a - 1,
               bounds=[(0, C)] * len(y), constraints={"type": "eq", "fun": lambda a: a @ y, "jac": lambda a: y},
               method="SLSQP", options={"ftol": 1e-12, "maxiter": 500})
a = res.x
w = (a * y) @ X                                        # w = sum a_i y_i x_i
free = (a > 1e-6) & (a < C - 1e-6)                    # support vectors exactly on the margin
b = np.mean(y[free] - X[free] @ w)
sv = np.flatnonzero(a > 1e-6)

sk = SVC(kernel="linear", C=C).fit(X, y)
print("ours    w", w.round(3), " b", round(b, 3))
print("sklearn w", sk.coef_[0].round(3), " b", round(sk.intercept_[0], 3))
print("support vectors ours", sv.tolist())
print("support vectors skl ", sorted(sk.support_.tolist()))
margins = y * (X @ w + b)
print("margin width 2/||w||:", round(2 / np.linalg.norm(w), 3))
print("points inside the margin or misclassified (y f(x) < 1):", int(np.sum(margins < 1 - 1e-6)),
      " misclassified:", int(np.sum(margins < 0)))
ours    w [1.341 0.761]  b -0.164
sklearn w [1.341 0.761]  b -0.164
support vectors ours [4, 15, 17, 19, 22, 23, 24, 26, 34, 37]
support vectors skl  [4, 15, 17, 19, 22, 23, 24, 26, 34, 37]
margin width 2/||w||: 1.297
points inside the margin or misclassified (y f(x) < 1): 8  misclassified: 2

The general solver and libsvm's specialised SMO algorithm (which SVC uses) find the same hyperplane and the same 10 support vectors out of 40 points. The other 30 points could be deleted without changing the model. Eight support vectors violate the margin (two of them are misclassified); the remaining two sit exactly on it and fix bb.

The primal by subgradient descent, and the role of C

The hinge loss has a kink at yf=1y f = 1, so it has no gradient there, but a subgradient works (Subgradients): for points with yif(xi)<1y_i f(\mathbf{x}_i) < 1 add −Cyixi-C y_i \mathbf{x}_i, for the others nothing. Plain subgradient descent with a decaying step size comes close to the exact optimum. Then the effect of CC:

python · try it yourself
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.svm import LinearSVC, SVC

X, y01 = make_blobs(n_samples=40, centers=[[-1.5, -1], [1.5, 1]], cluster_std=1.0, random_state=0)
y = np.where(y01 == 1, 1.0, -1.0)

def pegasos_like(X, y, C=1.0, epochs=2000, lr0=0.01):
    """Subgradient descent on the primal: 1/2 ||w||^2 + C * sum max(0, 1 - y (w.x + b))."""
    w, b = np.zeros(X.shape[1]), 0.0
    for t in range(epochs):
        lr = lr0 / (1 + t / 200)
        active = y * (X @ w + b) < 1                    # points with positive hinge loss
        gw = w - C * (y[active, None] * X[active]).sum(axis=0)
        gb = -C * y[active].sum()
        w, b = w - lr * gw, b - lr * gb
    return w, b

def primal(w, b, C=1.0):
    return 0.5 * w @ w + C * np.maximum(0, 1 - y * (X @ w + b)).sum()

w, b = pegasos_like(X, y)
sk = SVC(kernel="linear", C=1.0).fit(X, y)
print("subgradient  w", w.round(3), " b", round(b, 3), " objective", round(primal(w, b), 4))
print("SVC (exact)  w", sk.coef_[0].round(3), " b", round(sk.intercept_[0], 3), " objective", round(primal(sk.coef_[0], sk.intercept_[0]), 4))
for C in [0.01, 0.1, 1, 100]:
    m = SVC(kernel="linear", C=C).fit(X, y)
    print(f"C={C:<5}  margin width {2 / np.linalg.norm(m.coef_):.2f}  support vectors {len(m.support_):2d}  training accuracy {m.score(X, y):.3f}")
subgradient  w [1.337 0.762]  b -0.162  objective 7.4871
SVC (exact)  w [1.341 0.761]  b -0.164  objective 7.4861
C=0.01   margin width 5.00  support vectors 36  training accuracy 0.900
C=0.1    margin width 2.25  support vectors 18  training accuracy 0.950
C=1      margin width 1.30  support vectors 10  training accuracy 0.950
C=100    margin width 0.24  support vectors  5  training accuracy 0.975

Subgradient descent ends within 0.001 of the optimal objective. The CC sweep shows the trade-off: small CC makes violations cheap, so the street gets wide (5.00) and almost every point becomes a support vector; large CC punishes every violation, the street narrows to 0.24 and the boundary bends to the training points. CC plays the role of 1/α1/\alpha in ridge regression: it is an inverse regularisation strength, chosen by cross-validation. For large data, LinearSVC (liblinear) or SGDClassifier(loss="hinge") solve the primal much faster than SVC.

Try it in the lab with the linear SVM: the solid line is the boundary, the dashed lines the margins f=±1f = \pm 1, and circled points are support vectors. Change CC and watch the street.

−202−202feature x₁feature x₂linear SVM on blobsC = 1: 21 support vectorsclass Aclass Bdecision boundarysupport vectormarginTraining accuracy73/8091.3 %Test accuracy181/20090.5 %Test set: 200 new points

Strengths, weaknesses, when to use it

Strengths Weaknesses
convex problem, unique solution no probabilities (Platt scaling via probability=True adds them, at a cost)
depends only on support vectors; robust to points far from the boundary needs feature scaling
works well in high dimensions (text) kernel SVMs scale badly beyond about 10510^5 rows
kernels give nonlinear boundaries CC (and kernel parameters) must be tuned

Use a linear SVM for high-dimensional sparse data such as text, where it is as accurate as logistic regression and very fast with LinearSVC; use kernel SVMs for small to medium data sets with complex boundaries.

Pitfalls

  • Unscaled features. The margin is measured in feature units; a feature in thousands dominates it.
  • Reading decision_function as a probability. It is a signed distance-like score.
  • LinearSVC and SVC(kernel="linear") differ. LinearSVC defaults to the squared hinge and penalises the intercept, so coefficients differ slightly.

Practice

  1. A point has y=+1y = +1 and f(x)=0.4f(\mathbf{x}) = 0.4. What is its hinge loss, and is it a support vector?
Answer

max⁡(0,1−0.4)=0.6\max(0, 1 - 0.4) = 0.6. It is inside the margin (correct side, but yf<1yf < 1), so its αi=C\alpha_i = C and it is a support vector.

  1. Why does deleting a point with yif(xi)>1y_i f(\mathbf{x}_i) > 1 not change the SVM?
Answer

Its hinge loss and its subgradient are 0, and in the dual its αi=0\alpha_i = 0, so it contributes nothing to w=∑iαiyixi\mathbf{w} = \sum_i \alpha_i y_i \mathbf{x}_i. The optimum of the problem without it is the same.

Test yourself

What is the width of the margin of a linear SVM with weight vector w\mathbf{w}?

  1. ∥w∥\lVert \mathbf{w} \rVert
  2. 1/∥w∥1/\lVert \mathbf{w} \rVert
  3. 2/∥w∥2/\lVert \mathbf{w} \rVert
  4. CC

Which points determine a trained SVM?

  1. All training points equally
  2. Only the support vectors: points on or inside the margin
  3. Only misclassified points
  4. The class centroids

What happens to the margin as CC grows?

  1. It widens
  2. It narrows, because violations become expensive
  3. It stays the same
  4. It becomes nonlinear

How does the hinge loss differ from the logistic loss?

  1. It is not convex
  2. It is exactly zero for points beyond the margin
  3. It is always larger
  4. It needs probabilities