Find the best constant prediction under MSE, MAE and pinball loss with a grid search
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `mse(y_true, y_pred)`, `mae(y_true, y_pred)` and `pinball(y_true, y_pred, tau)` as mean losses (`y_pred` may be a scalar or an array), each returning a `float`. Then grid-search constant predictions: `constant_loss_curve(y_true, grid, loss, tau=0.5)` returns the loss of every grid value, and `best_constant(y_true, grid, loss, tau=0.5)` returns the grid value with the lowest loss.
- Pinball uses the residual `r = y - p` and takes the mean of `max(tau*r, (tau-1)*r)`, which matches scikit-learn's `mean_pinball_loss`.
- `loss` is `"mse"`, `"mae"` or `"pinball"` (which uses `tau`). Any other name raises `ValueError`.
- `constant_loss_curve` returns a float NumPy array of shape `(len(grid),)`.
- `best_constant` returns a `float`. Ties resolve to the first grid value.
For example:
```python
y = [1, 2, 3, 4, 40]
grid = np.round(np.linspace(0, 50, 5001), 2)
best_constant(y, grid, "mse") # 10.0 (mean)
best_constant(y, grid, "mae") # 3.0 (median)
best_constant(y, grid, "pinball", tau=0.7) # 4.0 (0.7-quantile)
best_constant([0, 1], [0, 0.5, 1], "mae") # 0.0 (tie, first wins)
```
```hint Scalars and ties
A constant prediction is a scalar, so each loss has to stretch `y_pred` to the shape of `y_true`. For the tie rule, check which index NumPy returns when the minimum value appears more than once.
```
### What a Strong Answer Covers
- Losses that accept a scalar or an array prediction through broadcasting and return plain Python floats.
- The pinball loss with the stated sign convention, so under-prediction is weighted by `tau`.
- Dispatch on the loss name with a `ValueError` for unknown names, a float curve of shape `(len(grid),)`, and first-index tie-breaking.
- Why the three optima are the mean, the median and the `tau`-quantile, checked against the example values.
### Follow-up Questions
- Why does the `mse` optimum sit above the `mae` optimum on a right-skewed target?
- How would you compute the whole loss curve without a Python loop over the grid, and what does that cost in memory?
- MAE on an even number of targets has a flat minimum. Which value does the grid search return there, and how does it compare with `np.median`?
Overview: Implement mean squared error, mean absolute error and pinball loss in NumPy, then grid-search the constant prediction that minimizes each one. Tests broadcasting a scalar prediction, the pinball sign convention, tie-breaking, and which summary statistic each loss is minimized by.