TExcelTAD
Home › Math for Machine Learning › Soft Margin and the Hinge Loss

Soft Margin and the Hinge Loss

Real data is rarely perfectly separable: a few points sit on the wrong side, and the hard-margin SVM then has no solution at all. The soft-margin SVM allows violations at a price. Rewritten without constraints, it becomes ordinary regularized risk minimization with the hinge loss, which can be trained with (sub)gradient descent like any other model.

Slack variables

Give each point a slack ξn≥0\xi_n \ge 0 that measures how much it violates the margin:

min⁡w,b,ξ 12∥w∥2+C∑n=1Nξns.t.yn(wTxn+b)≥1−ξn,  ξn≥0\min_{\mathbf{w}, b, \boldsymbol{\xi}}\ \frac{1}{2}\lVert \mathbf{w} \rVert^2 + C\sum_{n=1}^{N}\xi_n \quad \text{s.t.} \quad y_n(\mathbf{w}^T\mathbf{x}_n + b) \ge 1 - \xi_n,\ \ \xi_n \ge 0

ξn=0\xi_n = 0: correct and outside the margin; 0<ξn≤10 < \xi_n \le 1: inside the margin but correct; ξn>1\xi_n > 1: misclassified. The hyperparameter CC trades margin width against violations: large CC approaches the hard margin, small CC tolerates more errors for a wider margin.

The hinge-loss view

At the optimum, each slack is as small as allowed: ξn=max⁡(0,1−ynf(xn))\xi_n = \max(0, 1 - y_nf(\mathbf{x}_n)). Substituting removes the constraints:

min⁡w,b 12∥w∥2⏟regularizer+C∑nmax⁡(0, 1−yn(wTxn+b))⏟hinge loss\min_{\mathbf{w}, b}\ \underbrace{\frac{1}{2}\lVert \mathbf{w} \rVert^2}_{\text{regularizer}} + C\sum_{n}\underbrace{\max\big(0,\ 1 - y_n(\mathbf{w}^T\mathbf{x}_n + b)\big)}_{\text{hinge loss}}

This is empirical risk minimization with the hinge loss and an ℓ2\ell_2 penalty. Compared with the logistic loss, the hinge loss is exactly zero for points beyond the margin, which is why only the support vectors matter.

Subgradient descent

The hinge loss has a kink at margin 1, so we use a subgradient: for a point with ynf(xn)<1y_nf(\mathbf{x}_n) < 1 the hinge term contributes −ynxn-y_n\mathbf{x}_n to the gradient with respect to w\mathbf{w} (and −yn-y_n for bb); otherwise 0.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
Xp = rng.normal([2, 2], 0.9, size=(60, 2)); Xn = rng.normal([-1, -1], 0.9, size=(60, 2))
X = np.vstack([Xp, Xn]); y = np.concatenate([np.ones(60), -np.ones(60)])

def train(C, epochs=400, lr=0.01):
    w, b = np.zeros(2), 0.0
    for _ in range(epochs):
        m = y * (X @ w + b)
        active = m < 1                                   # points with nonzero 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

for C in (0.01, 0.1, 10.0):
    w, b = train(C)
    m = y * (X @ w + b)
    print(f"C={C:<5}: margin width {2 / np.linalg.norm(w):.3f}, train accuracy {np.mean(m > 0):.3f}, "
          f"points inside margin {int(np.sum(m < 1))}")
C=0.01 : margin width 3.760, train accuracy 1.000, points inside margin 43
C=0.1  : margin width 2.093, train accuracy 1.000, points inside margin 14
C=10.0 : margin width 0.687, train accuracy 1.000, points inside margin 1

Small CC gives a wide margin with many points inside it; large CC narrows the margin to fit the training points more tightly.

Hinge versus logistic

Both are convex upper bounds on the zero-one loss. Logistic regression gives calibrated probabilities and uses every point; the SVM gives a sparse solution (only margin violators matter) and no probabilities without extra calibration.

python · try it yourself
import numpy as np

m = np.array([-1.0, 0.0, 0.5, 1.0, 2.0, 4.0])
print("margin   :", m)
print("hinge    :", np.maximum(0, 1 - m))
print("logistic :", np.round(np.log1p(np.exp(-m)), 4))
margin   : [-1.   0.   0.5  1.   2.   4. ]
hinge    : [2.  1.  0.5 0.  0.  0. ]
logistic : [1.3133 0.6931 0.4741 0.3133 0.1269 0.0181]

In software

  • LinearSVC(C=...) minimizes this objective (with a squared hinge by default); SGDClassifier(loss="hinge") uses SGD.
  • SVC(probability=True) adds Platt scaling to turn SVM scores into probabilities.
  • The hinge loss also appears in ranking losses and in some GAN discriminators.

Exercises

Exercise 1: Slack values

With f(x)=wTx+bf(\mathbf{x}) = \mathbf{w}^T\mathbf{x} + b, three positive points have f=2,0.6,−0.5f = 2, 0.6, -0.5. Find their slacks.

Answer

00, 0.40.4, 1.51.5.

Solution

ξ=max⁡(0,1−yf)\xi = \max(0, 1 - yf) with y=1y = 1: max⁡(0,−1)=0\max(0, -1) = 0, 0.40.4, 1.51.5. The last one is misclassified (ξ>1\xi > 1).

Exercise 2: Subgradient

For w=(1,0)\mathbf{w} = (1, 0), b=0b = 0 and a point x=(0.5,2)\mathbf{x} = (0.5, 2) with y=1y = 1, what is the subgradient of the hinge term with respect to w\mathbf{w}?

Answer

(−0.5,−2)(-0.5, -2).

Solution

The margin is yf=0.5<1yf = 0.5 < 1, so the term is active and its subgradient is −yx=−(0.5,2)-y\mathbf{x} = -(0.5, 2).

Exercise 3: Count the violators (code)

For w=(1,1)\mathbf{w} = (1, 1), b=−1b = -1, compute the hinge losses of (1,1,+1)(1, 1, +1), (0.5,0.2,+1)(0.5, 0.2, +1), (0,0,−1)(0, 0, -1), (1,0.5,−1)(1, 0.5, -1) (last entry is the label).

Answer

00, 1.31.3, 00, 1.51.5.

Solution

Scores f=1,−0.3,−1,0.5f = 1, -0.3, -1, 0.5; margins yf=1,−0.3,1,−0.5yf = 1, -0.3, 1, -0.5.

python · try it yourself
import numpy as np
X = np.array([[1, 1], [0.5, 0.2], [0, 0], [1, 0.5]]); y = np.array([1, 1, -1, -1])
print(np.round(np.maximum(0, 1 - y * (X @ np.array([1.0, 1.0]) - 1)), 4))
[0.  1.3 0.  1.5]

Test yourself

The hinge loss max⁡(0,1−yf)\max(0, 1 - yf) is zero when…

  1. the point is misclassified
  2. the point is correctly classified with margin at least 1
  3. f=0f = 0
  4. always

Increasing CC in a soft-margin SVM…

  1. widens the margin and allows more violations
  2. penalizes violations more, narrowing the margin
  3. removes the regularizer
  4. changes the kernel

The soft-margin SVM objective is equivalent to…

  1. least squares
  2. ℓ2\ell_2-regularized empirical risk with the hinge loss
  3. maximum likelihood with Gaussian noise
  4. k-means