Brier Score and Brier Skill Score
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `brier_score(y_true, y_prob, sample_weight=None)`, the (optionally weighted) mean of `(p - y)**2`, and `brier_skill_score(y_true, y_prob, sample_weight=None)`, defined as `1 - BS / BS_ref`. `BS_ref` is the Brier score of a constant forecast equal to the (weighted) prevalence of `y_true`. Both return a Python `float`.
Both functions share these rules:
- `sample_weight=None` gives every sample weight 1.
- Raise `ValueError` when the lengths differ, the input is empty, a label is not 0 or 1, a probability is not a finite value in [0, 1], or the weights are negative, not finite, or sum to 0.
- `brier_skill_score` returns `nan` when `BS_ref` is 0, which happens when every sample with positive weight has the same label.
Examples:
```python
y = [1, 0, 1, 1]
p = [0.9, 0.2, 0.6, 0.4]
brier_score(y, p) # 0.1425
brier_skill_score(y, p) # 0.24 (prevalence 0.75, BS_ref = 0.1875)
y = [1, 0]
p = [0.5, 0.5]
sample_weight = [3, 1]
brier_score(y, p, sample_weight) # 0.25
brier_skill_score(y, p, sample_weight) # -1/3
```
```hint Reuse the score
The baseline is the Brier score of a different forecast. Write one weighted helper and call it twice, with the same weights both times.
```
### Constraints & Assumptions
- `y_true` holds binary labels, and `y_prob` holds the predicted probability of the positive class for each sample.
- Inputs may be lists or NumPy arrays. `sample_weight`, when given, has one weight per sample.
### What a Strong Answer Covers
- The weighted mean squared error between probabilities and 0/1 labels.
- A baseline built from the weighted prevalence and scored with the same weights as the model.
- What the skill score's sign and range mean, and the `nan` case when the baseline score is 0.
- Input validation shared by both functions.
- Linear time in the number of samples.
### Follow-up Questions
- Why is the Brier score a proper scoring rule, and why does that matter?
- How does the Brier score treat a confidently wrong prediction compared with log loss?
- How can the Brier score be split into calibration and resolution terms?
- A model has a high AUC but a negative Brier skill score. What could explain it?
Overview: Implement the weighted Brier score and the Brier skill score for binary probability forecasts, comparing a model against a constant prevalence baseline. It tests calibration metrics, sample weighting, input validation and the degenerate single-class case.