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 that measures how much it violates the margin:
: correct and outside the margin; : inside the margin but correct; : misclassified. The hyperparameter trades margin width against violations: large approaches the hard margin, small tolerates more errors for a wider margin.
The hinge-loss view
At the optimum, each slack is as small as allowed: . Substituting removes the constraints:
This is empirical risk minimization with the hinge loss and an 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 the hinge term contributes to the gradient with respect to (and for ); otherwise 0.
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 gives a wide margin with many points inside it; large 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.
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 , three positive points have . Find their slacks.
Answer
, , .
Solution
with : , , . The last one is misclassified ().
Exercise 2: Subgradient
For , and a point with , what is the subgradient of the hinge term with respect to ?
Answer
.
Solution
The margin is , so the term is active and its subgradient is .
Exercise 3: Count the violators (code)
For , , compute the hinge losses of , , , (last entry is the label).
Answer
, , , .
Solution
Scores ; margins .
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 is zero when…
- the point is misclassified
- the point is correctly classified with margin at least 1
- always
Increasing in a soft-margin SVM…
- widens the margin and allows more violations
- penalizes violations more, narrowing the margin
- removes the regularizer
- changes the kernel
The soft-margin SVM objective is equivalent to…
- least squares
- -regularized empirical risk with the hinge loss
- maximum likelihood with Gaussian noise
- k-means