Implement a Numerically Stable Log-Cosh Loss and Its Gradient
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `log_cosh_loss` and `log_cosh_grad` for the residual `r = y_pred - y_true`, with these signatures:
```python
def log_cosh_loss(y_true, y_pred, sample_weight=None, reduction="mean"): ...
def log_cosh_grad(y_true, y_pred, sample_weight=None, reduction="mean"): ...
```
The per-example loss is `w * log(cosh(r))` and must stay finite for huge residuals. The gradient is with respect to `y_pred` and must be computed via `tanh(r)`.
Example:
```python
log_cosh_loss([0, 0], [1, -2], reduction="none")
# -> [0.43378083, 1.32500275]
log_cosh_loss([0], [1000], reduction="none")
# -> [999.30685282] # |r| - log(2), no overflow
log_cosh_grad([0], [1000], reduction="none")
# -> [1.0]
```
```hint Avoid the big number
Rewrite `log(cosh(r))` so that the only exponential you ever evaluate has an exponent of 0 or less.
```
```hint Weighted mean
Work out the derivative of a weighted mean with respect to a single prediction before writing the `"mean"` branch of the gradient.
```
### Constraints & Assumptions
- `sample_weight` defaults to all ones. A shape mismatch between `y_true`, `y_pred` or the weights raises `ValueError`.
- `"none"` returns the per-example array, `"sum"` returns the float sum, and `"mean"` returns a float equal to the weighted sum divided by `sum(w)`.
- The gradient is `w * tanh(r)` for `"none"` and `"sum"`, divided by `sum(w)` for `"mean"`. It always returns an array shaped like `y_pred`.
- Any other `reduction` raises `ValueError` in both functions.
- `|r|` may be as large as `1e6`, and the results must be finite.
### What a Strong Answer Covers
- An overflow-free rewrite of `log(cosh(r))` and why it equals the original expression.
- The gradient through `tanh(r)`, with the sign that follows from `r = y_pred - y_true`.
- Every reduction in both functions, with the mean normalized by `sum(w)`.
- Shape validation and the `ValueError` for an unknown reduction.
- Numerical behavior at both ends: huge residuals and residuals near zero.
### Follow-up Questions
- How does log-cosh compare to Huber loss?
- What is the Hessian, and why might it be a problem in gradient boosting?
- What happens with the `"mean"` reduction if all weights are zero?
Overview: Implement the log-cosh regression loss and its gradient in NumPy with sample weights and none, sum and mean reductions. Tests rewriting a formula so it never overflows for residuals up to a million, deriving the gradient of a weighted mean, and careful input validation.