Linear SVM with Hinge Loss

medium
Unit 10 · Classification II0/2 to milestone

A linear support vector machine finds the separating line with the widest margin. Train it with (sub)gradient descent on the regularised hinge loss, for labels y∈{−1,+1}y \in \{-1, +1\}:

L=λ2∥w∥2+1n∑imax⁡(0,  1−yi(w⋅xi+b))\mathcal{L} = \frac{\lambda}{2}\|w\|^2 + \frac{1}{n}\sum_i \max(0,\; 1 - y_i(w \cdot x_i + b))

Subgradient: examples with margin yi(w⋅xi+b)<1y_i(w \cdot x_i + b) < 1 contribute −yixi-y_i x_i (and −yi-y_i for bb), averaged over nn; the regulariser contributes λw\lambda w (not to bb).

Implement hinge_loss(X, y, w, b, lam), train_svm(X, y, lam=0.01, lr=0.1, epochs=500) (full-batch, starting from zeros, returning (w, b)), predict_svm(X, w, b) (±1, with 0 mapping to +1) and support_vectors(X, y, w, b, tol=1e-3): the indices with margin ≤ 1 + tol.

#classification#svm#optimization2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Linear SVM with Hinge Loss · TechGradify