Sub topic 6
The SVM as regularized hinge-loss minimization
This chapter assumes you know the soft-margin SVM with slack variables and the role of C. It also assumes you can read NumPy and compute simple gradients. Here we rewrite the constrained soft-margin problem as an unconstrained loss function, which is the form used by most large-scale linear SVM solvers.
From slack variables to a loss function
The soft-margin SVM minimizes this objective over w, b and the slack values ξ_i:
0.5 ||w||^2 + C Σ ξ_i
It is subject to yi (w·xi + b) ≥ 1 − ξi and ξi ≥ 0.
For a fixed w and b, each slack value wants to be as small as the constraints allow. Two cases follow:
- If the point satisfies yi (w·xi + b) ≥ 1, then ξ_i = 0 is feasible, and it is the smallest allowed value.
- Otherwise the constraint forces ξi ≥ 1 − yi (w·x_i + b), and the smallest allowed value is exactly that.
Both cases combine into one expression:
ξi = max(0, 1 − yi (w·x_i + b))
Substituting this into the objective removes the constraints entirely. The result is an unconstrained problem:
min over w, b of 0.5 ||w||^2 + C Σ max(0, 1 − yi (w·xi + b))
The function max(0, 1 − m) is the hinge loss, where m = yi f(xi) is the functional margin of a point. The functional margin is positive when the point is on the correct side of the boundary, and its size grows with the distance from the boundary.
What the hinge loss does
The hinge loss is zero when m ≥ 1. It grows linearly as m falls below 1. Three regions matter:
| Functional margin m | Hinge loss | Meaning |
|---|---|---|
| m ≥ 1 | 0 | Correct and outside the margin. The point has no influence. |
| 0 ≤ m < 1 | 1 − m | Correct but inside the margin. It is penalized. |
| m < 0 | 1 − m (greater than 1) | Misclassified. The penalty grows linearly with the violation. |
Points with zero loss contribute nothing to the objective, which is why they do not affect the solution. This is the loss-function view of why only support vectors matter.
The hinge loss differs from the 0-1 loss, which simply counts mistakes. The 0-1 loss is not convex and gives no gradient information, so it cannot be minimized efficiently. The hinge loss is convex and acts as an upper bound on the 0-1 loss. Minimizing it therefore also limits the number of training errors.
The regularized view
The unconstrained objective has the standard form of regularized empirical risk:
loss on the data + penalty on model complexity
Here the data loss is C Σ hinge, and the penalty is 0.5 ||w||^2. The penalty is L2 regularization. Small ||w|| corresponds to a wide margin, because the geometric margin equals 1 / ||w||. So the regularizer and the margin-maximization idea are the same thing.
Many libraries write the objective in a different but equivalent way:
(λ / 2) ||w||^2 + (1/n) Σ hinge
Dividing the first objective by C n gives this form with λ = 1 / (C n). The relationship matters in practice:
- A large C corresponds to a small λ, meaning weak regularization and a narrow margin that fits the training data closely.
- A small C corresponds to a large λ, meaning strong regularization and a wide margin that tolerates more violations.
Be careful when comparing libraries. Some use C, some use λ or alpha, and some average the loss while others sum it. The same numeric value can mean different things.
Computing the objective in code
The function below evaluates the objective. It is the same computation as the soft-margin objective, written with the hinge loss. Labels must be in {-1, +1}.
import numpy as np
def hinge_objective(w, b, X, y, C):
margins = y * (X @ w + b)
slack = np.maximum(0.0, 1.0 - margins)
return 0.5 * np.dot(w, w) + C * slack.sum()The array slack holds the hinge loss of each point. It equals the optimal slack variable from the constrained problem. You can check this by fitting an SVC with a linear kernel and computing the objective at its coef_ and intercept_. Any other (w, b) should give a value that is equal or larger, up to solver tolerance.
Subgradient descent
The hinge loss is not differentiable at m = 1, where it has a kink. It is still convex, so we can use a subgradient, which is any valid slope at the kink. In practice we choose 0 there.
For one point, the subgradient of the hinge loss with respect to w is:
- −yi xi if yi f(xi) < 1
- 0 otherwise
Only points inside the margin or misclassified push the weights. The following code runs batch subgradient descent on the objective.
import numpy as np
from sklearn.datasets import make_blobs
def fit_linear_svm(X, y, C=1.0, lr=0.001, epochs=2000):
# y must contain labels in {-1, +1}
w = np.zeros(X.shape[1])
b = 0.0
for _ in range(epochs):
margins = y * (X @ w + b)
active = margins < 1.0
grad_w = w - C * (y[active, None] * X[active]).sum(axis=0)
grad_b = -C * y[active].sum()
w -= lr * grad_w
b -= lr * grad_b
return w, b
X, y01 = make_blobs(n_samples=100, centers=2, cluster_std=1.2, random_state=0)
y = 2 * y01 - 1
w, b = fit_linear_svm(X, y, C=1.0)
pred = np.sign(X @ w + b)
print("w:", w, "b:", b)
print("training accuracy:", (pred == y).mean())The gradient has two parts. The term w comes from the regularizer. The second term sums over only the active points, those with margin below 1. This matches the support-vector picture, because the active set is the set of margin violators plus points near the margin.
Production solvers improve on this loop. Stochastic methods such as Pegasos update on one example or a small batch with a decreasing step size. Coordinate descent on the dual, used by LIBLINEAR, is usually faster still for linear models.
Other losses in the same family
Viewing the SVM as a loss plus a penalty lets you compare it with related models.
| Model | Loss as a function of margin m | Properties |
|---|---|---|
| SVM | max(0, 1 − m) | Convex, exactly zero for m ≥ 1, sparse in the data |
| Squared hinge | max(0, 1 − m)^2 | Smooth, penalizes large violations more strongly |
| Logistic regression | log(1 + exp(−m)) | Smooth, never exactly zero, gives probabilities |
| 0-1 loss | 1 if m < 0 else 0 | Not convex, not practical to optimize |
In scikit-learn, LinearSVC uses the squared hinge loss by default, while SVC(kernel="linear") uses the plain hinge loss. They can give slightly different boundaries on the same data. LinearSVC also regularizes the intercept by default, which SVC does not.
Logistic loss and hinge loss behave similarly for badly misclassified points, since both grow roughly linearly. They differ near the boundary. The logistic loss still gives a small penalty to confidently correct points, so every point keeps some influence. The hinge loss gives them none.
Common errors
- Using labels 0 and 1 in a hand-written objective. The formula y * f(x) assumes labels in {-1, +1}. With 0/1 labels the loss is wrong, and every class-0 point gets a margin of zero.
- Forgetting to scale features. The penalty acts on w, so features with large scales dominate. Scale first, as covered in the scaling chapter.
- Assuming C means the same thing everywhere. As shown above, summed and averaged losses differ by a factor of n.
- Expecting a smooth optimum. Because the loss has kinks, plain gradient descent with a fixed large step size can oscillate. Use a decreasing step size or a library solver.
- Reading hinge-loss output as probabilities. The score f(x) is a signed distance-like value. Probability estimates need a separate calibration step, covered in a later chapter.
Exercise
A point has label y = +1 and score f(x) = 0.4. A second point has y = −1 and f(x) = 0.4. Compute the hinge loss of each, and say which would be a support vector or margin violator.
Show answer
For the first point, m = 1 × 0.4 = 0.4, so the loss is max(0, 1 − 0.4) = 0.6. It is correctly classified but inside the margin, so it is a margin violator. For the second point, m = −1 × 0.4 = −0.4, so the loss is max(0, 1.4) = 1.4. It is misclassified. Both have loss above zero, so both contribute to the objective and to the gradient.
Exercise
You change an objective from a sum of hinge losses with C = 10 to a mean of hinge losses on n = 500 samples. What value of the mean-form weight on the loss gives the same solution, and does the regularization get stronger or weaker if you keep the weight at 10 instead?
Show answer
The summed form C Σ hinge equals (C n) * mean hinge, so the equivalent weight on the mean loss is 10 × 500 = 5000. If you keep the weight at 10, the loss term is 500 times smaller relative to the penalty. Regularization becomes much stronger, so the margin is wider and the model underfits more.