Compute Stable Per-Sample Log Loss From Logits in NumPy
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement a function that returns the per-sample binary cross-entropy of a logistic regression model computed directly from its logits (the `decision_function` output).
```python
def stable_log_loss_from_logits(y_true: np.ndarray, z: np.ndarray) -> np.ndarray:
...
```
Requirements:
- Compute `loss_i = logaddexp(0, z_i) - y_i * z_i` using `np.logaddexp`.
- Return a `float64` array of shape `(n,)` with every entry finite.
- No clipping, no `sklearn.metrics.log_loss`, and never materialise `sigmoid(z)`.
Example:
```text
Input: y_true = [1, 0, 0, 1]
z = [-800.0, 800.0, 50.0, -50.0]
Output: [800.0, 800.0, 50.0, 50.0] (exact)
```
Every sample here is confidently wrong, so each loss is about `|z|`. In float64 the results are exactly these values.
```hint Where the formula comes from
Write the loss with $p = \sigma(z)$, then express $\log p$ and $\log(1-p)$ in terms of $z$ alone and simplify.
```
```hint Test the extremes
Evaluate each intermediate value at $z = 800$ and $z = -800$ in float64 and look for the step that overflows or takes $\log 0$.
```
### Constraints & Assumptions
- `y_true` is a 1-D array of 0/1 labels with shape `(n,)`.
- `z` is a 1-D array of raw logits with shape `(n,)`. Values can be extreme, for example `±800`.
- The function returns one loss per sample, not the mean.
### What a Strong Answer Covers
- The derivation from the probability form of binary cross-entropy to the logit form.
- Why `np.logaddexp(0, z)` stays finite at extreme logits and where the naive formulas overflow or hit `log(0)`.
- A vectorized implementation that returns a `float64` array of shape `(n,)` without clipping or forming the probability.
- A check of the example outputs, including why they come out exact.
- Time and space complexity.
### Follow-up Questions
- Why is `logaddexp(0, z)` stable while `log(1 + exp(z))` is not?
- How would you also return a numerically stable gradient of the loss with respect to `z`?
- How does the same idea carry over to softmax cross-entropy for more than two classes?
Overview: Implement per-sample binary cross-entropy in NumPy directly from logistic regression logits that can be as large as 800 in magnitude. The question tests the logit form of log loss, numerical stability in float64, and why naive formulas overflow or return infinity.