Implement Binary Log-Loss (Cross-Entropy) From Scratch in NumPy
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `def binary_log_loss(y_true: np.ndarray, y_pred: np.ndarray) -> float`. `y_true` holds 0/1 labels and `y_pred` holds P(y=1) per sample, both 1-D of shape `(n,)`. Return the mean per-sample binary cross-entropy as a Python `float`.
The function must:
- Compute `-(1/n) * sum(y*log(p) + (1-y)*log(1-p))` with the natural log (base e).
- Use NumPy directly: do not call `sklearn.metrics.log_loss`.
Example:
```python
y_true = [1, 0, 1, 1, 0]
y_pred = [0.9, 0.1, 0.8, 0.6, 0.3]
binary_log_loss(y_true, y_pred) # 0.26027303006691704
```
```hint Check the input types
The example passes plain Python lists. Think about what `1 - y_true` does on a list before you write the formula.
```
### Constraints & Assumptions
- `y_true` and `y_pred` have the same length n, and n is at least 1.
- Every label in `y_true` is 0 or 1.
- Every probability in `y_pred` lies strictly between 0 and 1, so both logs are always finite.
- Inputs may be NumPy arrays or plain Python lists, as in the example.
### What a Strong Answer Covers
- A vectorized NumPy computation of the per-sample term with the natural log, averaged over the n samples and negated.
- Converting both inputs to float arrays so that lists and integer labels work.
- Returning a plain Python `float`, as the signature promises.
- Time and space complexity of the computation.
- What goes wrong when a probability is exactly 0 or 1, and how to guard against it if the (0, 1) guarantee is removed.
### Follow-up Questions
- If some predictions can be exactly 0 or 1, how would you change the function, and how does the clipping constant affect the reported loss?
- The model gives you raw logits instead of probabilities. How would you compute the same loss without overflow or taking the log of zero?
- How would you support per-sample weights, and what should the denominator be?
- Why is log-loss a better metric than accuracy for judging the probabilities a classifier outputs?
Overview: Implement binary log-loss (binary cross-entropy) in NumPy without calling scikit-learn, returning the mean loss for 0/1 labels and predicted probabilities. It tests vectorized NumPy, the natural-log formula, input handling, and awareness of what happens when a probability reaches 0 or 1.