Reproduce sklearn log_loss Clipping Bit-For-Bit
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `sklearn_exact_log_loss(y_true, y_pred)` reproducing `sklearn.metrics.log_loss` (1.5) bit-for-bit without calling it. `y_true` is 1-D 0/1 labels and `y_pred` is 1-D $P(y=1)$, both shape `(n,)`, where `y_pred` contains exact `0.0` and `1.0`. Return the mean per-sample cross-entropy (natural log) as a Python `float`.
Requirements:
- Cast `y_pred` to float64.
- Use `eps = np.finfo(y_pred.dtype).eps` on the float64 array (`2.220446049250313e-16`, not `1e-15`).
- Clip to `[eps, 1 - eps]`.
- Per-sample loss: `-(y*log(p) + (1-y)*log(1-p))` with clipped `p`.
- Do not import or call `sklearn.metrics.log_loss`.
Example:
```python
y_true = np.array([1, 0, 1, 0])
y_pred = np.array([0.0, 1.0, 0.5, 0.25])
sklearn_exact_log_loss(y_true, y_pred)
# -> 18.26703400781151 (== sklearn.metrics.log_loss(y_true, y_pred))
```
```hint Find the dominant term
With exact 0.0 and 1.0 in the input, work out which rows dominate the mean and how directly their loss depends on the clipping bound.
```
```hint Check the arithmetic at the bound
Ask whether `1 - (1 - eps)` comes back as exactly `eps` in float64, and what that means for a row with label 0 and prediction 1.0.
```
### Constraints & Assumptions
- Both inputs are 1-D NumPy arrays of the same length `n`, and `y_true` holds only 0 and 1.
- `y_pred` holds probabilities in $[0, 1]$ and includes saturated values (exact `0.0` and `1.0`).
- The target is the value scikit-learn 1.5 returns with default arguments (no sample weights, mean over samples), matched exactly.
### What a Strong Answer Covers
- Identifies the clipping bound as what decides the result and uses the float64 machine epsilon.
- Casts before reading the epsilon, clips both ends, applies the natural-log binary cross-entropy, and returns the mean as a Python `float`.
- Explains why the saturated rows land exactly on $-\log(\varepsilon)$ in float64 arithmetic.
- Verifies the example value by hand.
- Names the ways a near-miss implementation goes wrong.
### Follow-up Questions
- Why does using `1e-15` instead of machine epsilon change the result?
- How would you generalize to multi-class `y_pred` of shape `(n, k)`?
- What would change if `y_pred` arrived as float32?
- Why does a library clip probabilities at all, and what does the bound imply about how much one confident wrong prediction can cost?
Overview: Reimplement scikit-learn's binary log loss so it matches the library to the last bit on inputs that contain exact 0 and 1 probabilities. It tests how probability clipping works, which epsilon applies to float64 arrays, and how small floating-point details change a reported metric.