Implement weighted MSE, MAE and Huber losses with reduction modes and gradients

Quick Overview

Implement weighted MSE, MAE and Huber losses in NumPy with none, sum and mean reductions, plus the gradient of the cost with respect to the predictions. Tests loss derivatives, weighted mean normalization and careful input validation.

Implement weighted MSE, MAE and Huber losses with reduction modes and gradients

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: easy

Interview Round: Other

Implement `compute_loss` and `loss_gradient` for 1-D arrays `y_true` and `y_pred`. With residual `r = y_pred - y_true`, `compute_loss` returns `(per_example_losses, cost)` and `loss_gradient` returns the derivative of the cost with respect to `y_pred`. Use these signatures: ```python def compute_loss(y_true, y_pred, loss="mse", reduction="mean", sample_weight=None, delta=1.0): ... def loss_gradient(y_true, y_pred, loss="mse", reduction="mean", sample_weight=None, delta=1.0): ... ``` Requirements: - `"mse"` is $r^2$, `"mae"` is $|r|$, and `"huber"` is ${0.5 r^2}$ when $|r| \le \delta$ and $\delta (|r| - 0.5\delta)$ otherwise. Per-example losses are returned unweighted. - The cost uses weights that default to 1. `"none"` returns the array $w \cdot \text{loss}$, `"sum"` returns the `float` $\sum w \cdot \text{loss}$, and `"mean"` returns the `float` $\sum w \cdot \text{loss} / \sum w$. - The gradient is $w \cdot \frac{d\,\text{loss}}{dr}$, divided by $\sum w$ for `"mean"`. MAE uses `np.sign(r)`, and Huber uses $r$ inside `delta` and $\delta \cdot \operatorname{sign}(r)$ outside. - Raise `ValueError` for non-1-D or mismatched shapes, an unknown `loss` or `reduction`, Huber with `delta <= 0`, a weight shape mismatch, or negative weights. - Raise `ValueError` for `"mean"` when the weights do not sum to a positive value. Example: ```python y_true = [1, 2, 3, 4]; y_pred = [1.5, 2, 1, 8]; w = [1, 2, 3, 4] compute_loss(y_true, y_pred, "mse", "none", w) # ([0.25, 0, 4, 16], [0.25, 0, 12, 64]) compute_loss(y_true, y_pred, "mse", "sum", w) # (..., 76.25) compute_loss(y_true, y_pred, "mse", "mean", w) # (..., 7.625) ``` ```hint Structure Compute the residual once, then treat the loss, the weighting and the reduction as separate steps. The gradient can follow the same steps with the elementwise derivative in place of the loss. ``` ```hint Weighted mean Pick the denominator of the weighted mean so that multiplying every weight by the same constant leaves the cost unchanged. ``` ### What a Strong Answer Covers - Correct per-example formulas for all three losses, including the Huber branch at $|r| = \delta$, returned without weights. - The three reductions with the right return types, and the weighted mean normalized by the weight sum. - Gradients that match each loss and reduction, including the MAE value at $r = 0$ and the ${1 / \sum w}$ factor applied only for `"mean"`. - Every listed input check raising `ValueError` before any arithmetic runs. - A vectorized NumPy implementation that runs in linear time. ### Follow-up Questions - How would you check `loss_gradient` numerically, and what step size and tolerance would you use near the MAE kink at $r = 0$ and the Huber threshold at $|r| = \delta$? - What happens to the `"mean"` cost when some weights are zero, and how would the result differ if you divided by `n`? - Why does the MAE gradient make gradient descent oscillate near the optimum, and how does Huber change that? - How would you extend both functions to multi-output targets of shape `(n, k)`?

Overview: Implement weighted MSE, MAE and Huber losses in NumPy with none, sum and mean reductions, plus the gradient of the cost with respect to the predictions. Tests loss derivatives, weighted mean normalization and careful input validation.

PracHub logo
General
Nov 24, 2026
easyMachine Learning EngineerOtherMachine Learning
0
0

Implement compute_loss and loss_gradient for 1-D arrays y_true and y_pred. With residual r = y_pred - y_true, compute_loss returns (per_example_losses, cost) and loss_gradient returns the derivative of the cost with respect to y_pred.

Use these signatures:

def compute_loss(y_true, y_pred, loss="mse", reduction="mean", sample_weight=None, delta=1.0): ...
def loss_gradient(y_true, y_pred, loss="mse", reduction="mean", sample_weight=None, delta=1.0): ...

Requirements:

  • "mse" is r2r^2 , "mae" is ∣r∣|r| , and "huber" is 0.5r2{0.5 r^2} when ∣r∣≤δ|r| \le \delta and δ(∣r∣−0.5δ)\delta (|r| - 0.5\delta) otherwise. Per-example losses are returned unweighted.
  • The cost uses weights that default to 1. "none" returns the array w⋅lossw \cdot \text{loss} , "sum" returns the float ∑w⋅loss\sum w \cdot \text{loss} , and "mean" returns the float ∑w⋅loss/∑w\sum w \cdot \text{loss} / \sum w .
  • The gradient is w⋅d lossdrw \cdot \frac{d\,\text{loss}}{dr} , divided by ∑w\sum w for "mean" . MAE uses np.sign(r) , and Huber uses rr inside delta and δ⋅sign⁡(r)\delta \cdot \operatorname{sign}(r) outside.
  • Raise ValueError for non-1-D or mismatched shapes, an unknown loss or reduction , Huber with delta <= 0 , a weight shape mismatch, or negative weights.
  • Raise ValueError for "mean" when the weights do not sum to a positive value.

Example:

y_true = [1, 2, 3, 4]; y_pred = [1.5, 2, 1, 8]; w = [1, 2, 3, 4]
compute_loss(y_true, y_pred, "mse", "none", w)  # ([0.25, 0, 4, 16], [0.25, 0, 12, 64])
compute_loss(y_true, y_pred, "mse", "sum",  w)  # (..., 76.25)
compute_loss(y_true, y_pred, "mse", "mean", w)  # (..., 7.625)

What a Strong Answer Covers Guidance

  • Correct per-example formulas for all three losses, including the Huber branch at ∣r∣=δ|r| = \delta , returned without weights.
  • The three reductions with the right return types, and the weighted mean normalized by the weight sum.
  • Gradients that match each loss and reduction, including the MAE value at r=0r = 0 and the 1/∑w{1 / \sum w} factor applied only for "mean" .
  • Every listed input check raising ValueError before any arithmetic runs.
  • A vectorized NumPy implementation that runs in linear time.

Follow-up Questions Guidance

  • How would you check loss_gradient numerically, and what step size and tolerance would you use near the MAE kink at r=0r = 0 and the Huber threshold at ∣r∣=δ|r| = \delta ?
  • What happens to the "mean" cost when some weights are zero, and how would the result differ if you divided by n ?
  • Why does the MAE gradient make gradient descent oscillate near the optimum, and how does Huber change that?
  • How would you extend both functions to multi-output targets of shape (n, k) ?