F1-maximising threshold
Problem
The candidate thresholds are the distinct values in scores; predict positive when score ≥ t. F1 is 0 when there are no true positives. Return (t, best_f1); if several thresholds tie, return the highest threshold.
Signature
def best_f1_threshold(y_true: list[int], scores: list[float]) -> tuple[float, float]: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> close(best_f1_threshold([0, 1, 1], [0.1, 0.8, 0.9]), (0.8, 1.0))
True
>>> close(best_f1_threshold([1, 0, 1], [0.9, 0.8, 0.1]), (0.1, 0.8))
TrueHints
Sweep candidate thresholds over the scores; compute F1 at each.
F1 = 2 * precision * recall / (precision + recall).
Keep the best (threshold-tie rule from the reference); return (best_f1, best_threshold).
Reference solution
def best_f1_threshold(y_true, scores):
best = None
for t in sorted(set(scores), reverse=True):
tp = sum(1 for y, s in zip(y_true, scores) if s >= t and y == 1)
fp = sum(1 for y, s in zip(y_true, scores) if s >= t and y == 0)
fn = sum(1 for y, s in zip(y_true, scores) if s < t and y == 1)
f1 = 0.0 if tp == 0 else 2 * tp / (2 * tp + fp + fn)
if best is None or f1 > best[1] + 1e-12:
best = (t, f1)
return bestWhat a strong solution covers
- Correct confusion counts at each threshold.
- Follow-up: O(n log n) sweep after sorting with running counts.
- Explains why cost-based thresholds may beat F1, and to tune on validation, not test.
Common mistakes
- using
>instead of≥ - picking thresholds on test data (discussion).