Sub topic 6
The SVM as regularized hinge-loss minimization
This chapter assumes you know the soft-margin SVM with slack variables and the parameter C, and that you are comfortable with gradients and NumPy. It shows that the constrained soft-margin problem is the same as an unconstrained loss function, which is the form most other classifiers use.
Eliminating the slack variables
The soft-margin problem is:
minimize 0.5·‖w‖² + C·Σ ξᵢ, subject to yᵢ(w·xᵢ + b) ≥ 1 − ξᵢ and ξᵢ ≥ 0.
For fixed w and b, each ξᵢ should be as small as its two constraints allow. That gives ξᵢ = max(0, 1 − yᵢ(w·xᵢ + b)). This is the hinge loss of point i. Substituting it back removes the constraints:
minimize 0.5·‖w‖² + C·Σ max(0, 1 − yᵢ f(xᵢ)), where f(x) = w·x + b.
The first term is an L2 penalty, as in ridge regression. The second term is the data-fit loss.
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.svm import SVC
def hinge_objective(w, b, X, y, C):
# y must contain labels in {-1, +1}
margins = y * (X @ w + b)
slack = np.maximum(0.0, 1.0 - margins)
return 0.5 * np.dot(w, w) + C * slack.sum()
X, y01 = make_blobs(n_samples=100, centers=2, cluster_std=1.2, random_state=0)
y = 2 * y01 - 1
clf = SVC(kernel="linear", C=1.0).fit(X, y)
w, b = clf.coef_[0], clf.intercept_[0]
print("fitted:", hinge_objective(w, b, X, y, 1.0))
print("w halved:", hinge_objective(0.5 * w, b, X, y, 1.0))The fitted solution minimizes this convex objective, so the second value should be larger.
Comparing loss functions
Hinge loss is zero once a point has margin yf(x) ≥ 1. Below that it grows linearly.
| Loss | Convex | Zero for confident correct points | Typical model |
|---|---|---|---|
| 0-1 loss | No | Yes | None (hard to optimize) |
| Hinge | Yes | Yes, beyond margin 1 | SVM |
| Logistic | Yes | No, only approaches 0 | Logistic regression |
Hinge loss is a convex upper bound on the 0-1 loss, so minimizing it is tractable. Because it is exactly zero beyond the margin, only points inside or on the wrong side of the margin contribute to the gradient. These are the support vectors.
Reading C as a regularization strength
Dividing the objective by nC gives (1/n)·Σ hinge + (λ/2)·‖w‖², with λ = 1/(nC). A large C means weak regularization and a tight fit to the training data. A small C means strong regularization and a wider, simpler margin.
Optimizing the primal directly
The hinge loss is not differentiable at margin 1, but it has a subgradient. For point i it is −yᵢxᵢ when yᵢf(xᵢ) < 1, and 0 otherwise. This is why linear SVMs can be trained by stochastic subgradient descent, as in SGDClassifier(loss="hinge").
Exercise
A point has label y = +1 and f(x) = 0.4. What is its hinge loss, and is it a support vector candidate?
Show answer
The margin is 1 × 0.4 = 0.4, so the hinge loss is max(0, 1 − 0.4) = 0.6. The point is correctly classified but lies inside the margin. Its loss is positive, so it contributes to the objective and is a support vector.