Vectorized Huber Loss and Gradient
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement two NumPy functions, `huber_loss(y_true, y_pred, delta=1.0)` and `huber_gradient(y_true, y_pred, delta=1.0)`, without Python loops.
With residual `r = y_pred - y_true`, the per-element Huber loss is `0.5 * r**2` when `|r| <= delta` and `delta * (|r| - 0.5 * delta)` otherwise. `huber_loss` returns the mean over all elements as a Python `float`. `huber_gradient` returns the derivative of that mean loss with respect to `y_pred`, with the same shape as `y_pred`.
For example:
```python
y_true = [0, 0, 0, 0]
y_pred = [0.5, -2.0, 1.0, 3.0]
huber_loss(y_true, y_pred, delta=1.0) # 1.15625, which is (0.125 + 1.5 + 0.5 + 2.5) / 4
huber_gradient(y_true, y_pred, delta=1.0) # [0.125, -0.25, 0.25, 0.25], which is [0.5, -1.0, 1.0, 1.0] / 4
```
```hint Where to start
Differentiate each branch of the loss with respect to `r` and compare the two results at `|r| = delta`. Then check what `np.where` computes for the elements it does not select, since residuals here can reach `1e150`.
```
### Constraints & Assumptions
- Inputs are array-likes of any shape (lists, nested lists or NumPy arrays). The mean is taken over all `n` elements.
- Mismatched shapes or `delta <= 0` raise `ValueError` in both functions.
- Residuals may be as large as `1e150` in absolute value. The loss and the gradient must stay finite.
- Use vectorized NumPy operations only, with no Python loop over elements.
### What a Strong Answer Covers
- Conversion of the inputs to float arrays and the two `ValueError` checks, applied the same way in both functions.
- A loop-free loss that matches both branches of the formula and returns a Python `float`.
- A gradient derived branch by branch, divided by `n` because the loss is a mean, and shaped like `y_pred`.
- Why the results stay finite for residuals near `1e150`, including what happens to the branch that `np.where` discards.
- Time and space complexity.
### Follow-up Questions
- Why is Huber loss less sensitive to outliers than MSE?
- How would you choose `delta`, and what does the loss turn into as `delta` goes to 0 or grows very large?
- Huber loss has no second derivative at `|r| = delta`. When does that matter, and what smooth alternative would you use?
- For a linear model `y_pred = X @ w`, how do you turn this gradient into the gradient with respect to `w`?
Overview: Implement the Huber loss and its gradient in NumPy without Python loops, returning the mean loss as a float and a gradient shaped like the predictions. It tests deriving a piecewise gradient, validating inputs, and keeping the math finite when residuals reach 1e150.