Log Loss From Scratch With Mean and Sum Reduction
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `log_loss_reduction(y_true, y_pred, normalize=True)` that reproduces the `normalize` semantics of `sklearn.metrics.log_loss` from scratch. Do not call `log_loss`. `y_true` holds 0/1 labels and `y_pred` holds $P(y=1)$ strictly inside $(0, 1)$, both 1-D with shape `(n,)`.
Requirements:
- The per-sample loss is `-(y*ln(p) + (1-y)*ln(1-p))`, using the natural log.
- With `normalize=True`, return the mean of the per-sample losses. With `normalize=False`, return their sum.
- Return a Python `float`.
Example:
```python
y_true = [1, 0, 1, 1, 0]
y_pred = [0.9, 0.1, 0.8, 0.6, 0.3]
log_loss_reduction(y_true, y_pred, normalize=True) # 0.26027303006691704
log_loss_reduction(y_true, y_pred, normalize=False) # 1.3013651503345853
```
```hint One vector, two reductions
Compute the per-sample losses once. The two settings of `normalize` differ only in the last step.
```
### Constraints & Assumptions
- `y_true` and `y_pred` are 1-D and have the same length `n`.
- Every entry of `y_pred` is strictly between 0 and 1, so both logarithms are finite.
- The inputs may be Python lists, as in the example, or NumPy arrays.
### What a Strong Answer Covers
- The per-sample binary cross-entropy with the natural log, vectorized over the arrays
- How `normalize` maps to the mean and the sum, and why both come from the same per-sample vector
- Converting the inputs to float arrays and returning a plain Python `float`
- Why clipping is unnecessary under the stated input guarantee, and what would happen at exactly 0 or 1
- Time and space complexity
### Follow-up Questions
- How does `log_loss` avoid `log(0)` when a prediction sits at exactly 0 or 1?
- How would you extend this to the multiclass case with a probability matrix of shape `(n, k)`?
- If the model gives you logits instead of probabilities, how would you compute the same loss without losing precision?
Overview: Implement binary log loss from scratch in NumPy and reproduce the normalize flag of scikit-learn's log_loss, which switches between a mean and a sum. Tests the cross-entropy formula, vectorized array code, input handling and how the reduction choice changes the returned value.