Implement a Linear Soft-Margin SVM with Full-Batch Subgradient Descent

Quick Overview

Implement a binary soft-margin linear SVM in NumPy trained with full-batch subgradient descent on the hinge-loss primal objective, with fit, predict and an objective history. Tests whether you can derive the subgradient at the hinge kink, keep the bias unregularized, validate inputs and explain why the objective does not always decrease.

Implement a Linear Soft-Margin SVM with Full-Batch Subgradient Descent

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Complete `LinearSVM` so it trains a binary soft-margin linear SVM with full-batch subgradient descent on $$ J(w, b) = \frac{1}{2}\lVert w \rVert^2 + C \sum_i \max\bigl(0,\ 1 - y_i (w \cdot x_i + b)\bigr). $$ Implement `objective`, `fit`, `decision_function` and `predict`. - Initialize `w` to zeros and `b = 0`. The bias is not regularized. Run exactly `epochs` updates, then store `w_` (array) and `b_` (float). `fit` returns `self`. - A sample is active only when its margin $y_i f(x_i) < 1$ (strictly). The subgradients are `grad_w = w - C * sum_active(y_i * x_i)` and `grad_b = -C * sum_active(y_i)`. - `objective_history_` is a list of length `epochs + 1`: the objective at initialization, then after each update. - `decision_function` returns `X @ w_ + b_`. `predict` returns int labels: `1` when the score is `>= 0`, else `-1`. - Labels outside {-1, +1} (in `fit` or `objective`) or a mismatch between the rows of `X` and `y` raise `ValueError`. Example: ```python X = np.array([[1., 2.], [2., 0.], [-1., -1.]]) y = np.array([1, 1, -1]) m = LinearSVM(C=1.0, learning_rate=0.1, epochs=1).fit(X, y) m.objective_history_[0] # 3.0 m.w_, m.b_ # array([0.4, 0.3]), 0.1 ``` ```hint One mask for both gradients A boolean mask over the margins tells you which samples contribute. Find a way to use it for both `grad_w` and `grad_b` without a Python loop over samples. ``` ```hint Check one step by hand Work out the first update on the three-point example before running anything. It catches a sign error in `grad_b` and an off-by-one in the history length. ``` ### Constraints & Assumptions - The constructor is `LinearSVM(C=1.0, learning_rate=0.01, epochs=1000)`. - `objective(X, y)` uses the currently stored `w_` and `b_`, which may be set manually instead of by `fit`. - Use NumPy only. ### What a Strong Answer Covers - Computes the objective with the unregularized bias and the full hinge sum, reading the stored `w_` and `b_`. - Uses the strict `margin < 1` active set and the correct signs in both subgradients, and runs exactly `epochs` updates. - Records `epochs + 1` objective values, starting with the value at initialization. - Validates labels in both `fit` and `objective` and checks that `X` and `y` have the same number of rows. - States the cost per epoch and explains why the objective can rise from one epoch to the next. ### Follow-up Questions - How would you make this scale to millions of samples? - Why does the objective history not always decrease monotonically? - How would you recover the dual coefficients or identify support vectors?

Overview: Implement a binary soft-margin linear SVM in NumPy trained with full-batch subgradient descent on the hinge-loss primal objective, with fit, predict and an objective history. Tests whether you can derive the subgradient at the hinge kink, keep the bias unregularized, validate inputs and explain why the objective does not always decrease.

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

Complete LinearSVM so it trains a binary soft-margin linear SVM with full-batch subgradient descent on

J(w,b)=12∥w∥2+C∑imax⁡(0, 1−yi(w⋅xi+b)).J(w, b) = \frac{1}{2}\lVert w \rVert^2 + C \sum_i \max\bigl(0,\ 1 - y_i (w \cdot x_i + b)\bigr).

Implement objective, fit, decision_function and predict.

  • Initialize w to zeros and b = 0 . The bias is not regularized. Run exactly epochs updates, then store w_ (array) and b_ (float). fit returns self .
  • A sample is active only when its margin yif(xi)<1y_i f(x_i) < 1 (strictly). The subgradients are grad_w = w - C * sum_active(y_i * x_i) and grad_b = -C * sum_active(y_i) .
  • objective_history_ is a list of length epochs + 1 : the objective at initialization, then after each update.
  • decision_function returns X @ w_ + b_ . predict returns int labels: 1 when the score is >= 0 , else -1 .
  • Labels outside {-1, +1} (in fit or objective ) or a mismatch between the rows of X and y raise ValueError .

Example:

X = np.array([[1., 2.], [2., 0.], [-1., -1.]])
y = np.array([1, 1, -1])
m = LinearSVM(C=1.0, learning_rate=0.1, epochs=1).fit(X, y)
m.objective_history_[0]  # 3.0
m.w_, m.b_               # array([0.4, 0.3]), 0.1

Constraints & Assumptions

  • The constructor is LinearSVM(C=1.0, learning_rate=0.01, epochs=1000) .
  • objective(X, y) uses the currently stored w_ and b_ , which may be set manually instead of by fit .
  • Use NumPy only.

What a Strong Answer Covers Guidance

  • Computes the objective with the unregularized bias and the full hinge sum, reading the stored w_ and b_ .
  • Uses the strict margin < 1 active set and the correct signs in both subgradients, and runs exactly epochs updates.
  • Records epochs + 1 objective values, starting with the value at initialization.
  • Validates labels in both fit and objective and checks that X and y have the same number of rows.
  • States the cost per epoch and explains why the objective can rise from one epoch to the next.

Follow-up Questions Guidance

  • How would you make this scale to millions of samples?
  • Why does the objective history not always decrease monotonically?
  • How would you recover the dual coefficients or identify support vectors?