Implement mean binary cross-entropy from scratch in NumPy when predicted probabilities can be exactly 0 or 1. It checks numerically safe clipping with a given epsilon, the natural-log loss formula, and how the epsilon caps the penalty for confident mistakes.
Implement `clipped_log_loss(y_true, y_pred, eps=1e-15)`, the mean binary cross-entropy `-(y * ln(p) + (1 - y) * ln(1 - p))`, from scratch. `y_pred` may contain exactly `0.0` or `1.0`, so the result must still be a finite Python `float`.
Requirements:
- Clip `y_pred` into `[eps, 1 - eps]` with `np.clip` before any logarithm.
- Use the `eps` argument. Do not hard-code a different epsilon.
- Do not call `sklearn.metrics.log_loss` (its internal epsilon differs).
- Use the natural log and return the mean.
For example:
```python
y_true = [1, 0, 1, 0]
y_pred = [0.0, 1.0, 0.5, 0.25] # eps = 1e-15 (default)
clipped_log_loss(y_true, y_pred)
# -> 17.514795410065823
```
```hint Both log terms
Look at the first two example rows. Whatever bound you put on `p` has to keep `ln(p)` and `ln(1 - p)` finite at the same time.
```
### Constraints & Assumptions
- Inputs are equal-length `np.ndarray`s.
- `y_true` holds binary labels (`0` or `1`).
- `y_pred` holds probabilities in `[0, 1]`, endpoints included.
- `eps` defaults to `1e-15`.
### What a Strong Answer Covers
- Clipping `y_pred` into `[eps, 1 - eps]` with the passed-in `eps` before any logarithm
- The per-sample natural-log formula, averaged and returned as a Python `float`
- Why a single clip keeps both log terms finite
- How `eps` caps the loss of a confidently wrong prediction
- Time and space complexity
### Follow-up Questions
- Why is clipping `y_pred` once enough to keep both `ln(p)` and `ln(1 - p)` finite?
- How does the choice of `eps` affect the loss for confidently wrong predictions?
- If the model gives you logits instead of probabilities, how would you compute the same loss without clipping?
Overview: Implement mean binary cross-entropy from scratch in NumPy when predicted probabilities can be exactly 0 or 1. It checks numerically safe clipping with a given epsilon, the natural-log loss formula, and how the epsilon caps the penalty for confident mistakes.
Implement clipped_log_loss(y_true, y_pred, eps=1e-15), the mean binary cross-entropy -(y * ln(p) + (1 - y) * ln(1 - p)), from scratch. y_pred may contain exactly 0.0 or 1.0, so the result must still be a finite Python float.
Requirements:
Clip
y_pred
into
[eps, 1 - eps]
with
np.clip
before any logarithm.
Use the
eps
argument. Do not hard-code a different epsilon.
Do not call
sklearn.metrics.log_loss
(its internal epsilon differs).