Train a regression that shrugs off outliers with the Huber loss

Squared error punishes a residual of 100 ten thousand times more than a residual of 1, so a few broken labels can drag the whole line. The Huber loss is squared for small residuals and linear for large ones, which caps the pull of any single point.

Write huber_regression(X, y, delta, lr, steps). X has shape (n, d), y has shape (n,). Fit y close to X @ w + b with full-batch gradient descent, starting from w = 0 and b = 0.

For residual r = X @ w + b - y, the Huber loss per point is 0.5 * r^2 when |r| <= delta, else delta * (|r| - 0.5 * delta). Minimise the mean loss. Its derivative with respect to r is r clipped to [-delta, delta].

Each step: compute g = clip(r, -delta, delta), then w -= lr * X.T @ g / n and b -= lr * mean(g). Run exactly steps updates. Return (w, b) with w a NumPy array and b a float.

Signaturedef huber_regression(X, y, delta, lr, steps)

Understand the idea

Squared error lets a few broken labels dominate, because their huge residuals get squared. The Huber loss acts like squared error for small residuals and like absolute error for large ones, so no single point can pull too hard. Its derivative is simply the residual clipped to [-delta, delta]. Like a tug of war where each person's pull is capped. Worked example, delta = 1: residuals [0.5, -3, 10]. Losses: 0.5 x 0.25 = 0.125; 1 x (3 - 0.5) = 2.5; 1 x (10 - 0.5) = 9.5. Gradients g = clip(r) = [0.5, -1, 1], so the residual of 10 pulls no harder than the residual of 3. With squared error the gradient would be [0.5, -3, 10]. Rule: start w = 0, b = 0; each step r = X w + b - y, g = clip(r, -delta, delta), w -= lr X^T g / n, b -= lr mean(g); run exactly the given number of steps. Robust regression on noisy labels and some reinforcement learning value losses use Huber loss.

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

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

  • Sample 1: one stephuber_regression([[1.0], [2.0]], [3.0, 10.0], 1.0, 0.5, 1)
  • Sample 2: outliershuber_regression(_X, _y, 1.0, 0.1, 300)
  • Test 3: small deltahuber_regression(_X, _y, 0.2, 0.2, 200)