Pegasos Solver for Linear SVM

Quick Overview

Implement the Pegasos stochastic subgradient solver for a bias-free linear SVM in NumPy, covering the primal hinge-loss objective, one update step with optional projection, a training loop and a predictor. It tests step-size schedules, margin checks and careful array handling.

Pegasos Solver for Linear SVM

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement the Pegasos stochastic subgradient solver for a bias-free linear SVM with labels in `{-1, +1}`. Write the primal objective, a single update step, a training loop over a given index sequence, and a predictor. The functions to implement: - `svm_objective(w, X, y, lam)` returns a Python `float`: `lam/2·||w||² + mean(max(0, 1 - y_i·<w, x_i>))`. - `pegasos_step(w, x, y, lam, t, project=False)`: with `eta = 1/(lam·t)`, set `w ← (1 - eta·lam)·w`, then add `eta·y·x` only if the margin (computed on the old `w`) is strictly `< 1`. Return a new array without mutating the input `w`. If `project=True`, rescale the updated `w` onto the ball of radius `1/sqrt(lam)` only when its norm exceeds that radius. - `pegasos_train(X, y, lam, indices, project=False)`: start from `w = 0` and visit `indices` in order with `t = 1, 2, ...`. - `predict(w, X)` returns an `int` array of `sign(<w, x>)`, with a score of `0` mapped to `+1`. For example: ```python pegasos_step(np.zeros(2), np.array([1.0, 2.0]), 1, 0.5, 1) # -> [2.0, 4.0] (eta = 2, margin 0 < 1) pegasos_step(np.zeros(2), np.array([1.0, 2.0]), 1, 0.5, 1, project=True) # -> [2.0, 4.0] * sqrt(2) / sqrt(20), about [0.632, 1.265] (the result has norm 1/sqrt(0.5)) pegasos_train(np.array([[1.0, 0.0], [0.0, 1.0]]), np.array([1, -1]), 1.0, [0, 1, 0]) # -> [2/3, -1/3] ``` ```hint First step Work out the shrink factor `1 - eta·lam` at `t = 1` and see what it does to the starting `w`. ``` ```hint Mutation pitfall In-place NumPy operations such as `w *= c` change the caller's array, and the margin test needs the old `w` anyway. ``` ### Constraints & Assumptions - `lam > 0`, `t ≥ 1`, and `indices` are valid row indices into `X` (repeats allowed). - `y` values are `-1` or `+1`. There is no bias term. ### What a Strong Answer Covers - The primal objective with the `lam/2` regularizer and the mean hinge loss, computed in vectorized form. - An update step that tests the margin on the old `w`, treats a margin of exactly 1 as no violation, and returns a fresh array. - The optional projection, applied only when the norm exceeds `1/sqrt(lam)`. - A training loop where `t` starts at 1 and follows the order of `indices`, and a predictor that sends a score of 0 to `+1`. - The time cost of training, the objective and prediction. ### Follow-up Questions - How would you extend this to mini-batch Pegasos? - Why is the projection onto the `1/sqrt(lam)` ball safe? - How would you add a bias term or return an averaged iterate?

Overview: Implement the Pegasos stochastic subgradient solver for a bias-free linear SVM in NumPy, covering the primal hinge-loss objective, one update step with optional projection, a training loop and a predictor. It tests step-size schedules, margin checks and careful array handling.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement the Pegasos stochastic subgradient solver for a bias-free linear SVM with labels in {-1, +1}. Write the primal objective, a single update step, a training loop over a given index sequence, and a predictor.

The functions to implement:

  • svm_objective(w, X, y, lam) returns a Python float : lam/2·||w||² + mean(max(0, 1 - y_i·<w, x_i>)) .
  • pegasos_step(w, x, y, lam, t, project=False) : with eta = 1/(lam·t) , set w ← (1 - eta·lam)·w , then add eta·y·x only if the margin (computed on the old w ) is strictly < 1 . Return a new array without mutating the input w . If project=True , rescale the updated w onto the ball of radius 1/sqrt(lam) only when its norm exceeds that radius.
  • pegasos_train(X, y, lam, indices, project=False) : start from w = 0 and visit indices in order with t = 1, 2, ... .
  • predict(w, X) returns an int array of sign(<w, x>) , with a score of 0 mapped to +1 .

For example:

pegasos_step(np.zeros(2), np.array([1.0, 2.0]), 1, 0.5, 1)
# -> [2.0, 4.0]   (eta = 2, margin 0 < 1)
pegasos_step(np.zeros(2), np.array([1.0, 2.0]), 1, 0.5, 1, project=True)
# -> [2.0, 4.0] * sqrt(2) / sqrt(20), about [0.632, 1.265]   (the result has norm 1/sqrt(0.5))
pegasos_train(np.array([[1.0, 0.0], [0.0, 1.0]]), np.array([1, -1]), 1.0, [0, 1, 0])
# -> [2/3, -1/3]

Constraints & Assumptions

  • lam > 0 , t ≥ 1 , and indices are valid row indices into X (repeats allowed).
  • y values are -1 or +1 . There is no bias term.

What a Strong Answer Covers Guidance

  • The primal objective with the lam/2 regularizer and the mean hinge loss, computed in vectorized form.
  • An update step that tests the margin on the old w , treats a margin of exactly 1 as no violation, and returns a fresh array.
  • The optional projection, applied only when the norm exceeds 1/sqrt(lam) .
  • A training loop where t starts at 1 and follows the order of indices , and a predictor that sends a score of 0 to +1 .
  • The time cost of training, the objective and prediction.

Follow-up Questions Guidance

  • How would you extend this to mini-batch Pegasos?
  • Why is the projection onto the 1/sqrt(lam) ball safe?
  • How would you add a bias term or return an averaged iterate?