Train a linear SVM with hinge loss subgradient descent

A linear SVM looks for the boundary with the widest margin. The hinge loss is not differentiable at margin 1, so you train it with a subgradient, the same way ReLU networks handle their kink.

Write svm_train(X, y, lam, lr, steps). X has shape (n, d), labels y are -1 or +1. Minimise (lam / 2) * ||w||^2 + mean(max(0, 1 - y_i * (w @ x_i + b))). The bias b is not regularised.

Start from w = 0, b = 0 and run exactly steps full-batch updates. A point is active when its margin y_i * (w @ x_i + b) < 1 (exactly 1 is not active). Subgradients:
- grad_w = lam * w - sum over active i of y_i * x_i, divided by n
- grad_b = - sum over active i of y_i, divided by n
Update w -= lr * grad_w and b -= lr * grad_b.

Return (w, b) with w a NumPy array and b a float.

Signaturedef svm_train(X, y, lam, lr, steps)

Understand the idea

A linear SVM looks for the boundary with the widest safety margin. The hinge loss max(0, 1 - y x score) is zero for points safely on the right side (margin at least 1) and grows linearly otherwise. It has a kink at margin 1, so you use a subgradient: only active points, those with margin below 1, contribute. The penalty lam / 2 x |w|^2 keeps w small, which widens the margin; the bias is not penalised. Worked example: X = [[1], [-1]], y = [1, -1], lam = 0.1, lr = 0.5, start w = 0, b = 0. Both margins are 0, so both are active. grad_w = 0.1 x 0 - (1 x 1 + (-1)(-1)) / 2 = -1; grad_b = -(1 - 1) / 2 = 0. New w = 0.5. Step 2: margins 0.5, still active; grad_w = 0.05 - 1 = -0.95; w = 0.5 + 0.475 = 0.975. Rule: active if y_i (w . x_i + b) < 1; grad_w = lam w - sum_active y_i x_i / n; grad_b = - sum_active y_i / n. SVMs were the leading classifiers before deep learning.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: two stepssvm_train([[2.0, 0.0], [-1.0, 0.0]], [1, -1], 0.1, 0.5, 2)
  • Sample 2: blobssvm_train(_X, _y, 0.5, 0.1, 200)
  • Test 3: weak regularisationsvm_train(_X, _y, 0.01, 0.05, 300)