---
title: F1-maximising threshold
url: https://gurkanozkan.ai/learn/coding/mle-f1-maximising-threshold-17/
markdown: https://gurkanozkan.ai/learn/coding/mle-f1-maximising-threshold-17.md
kind: coding
difficulty: Easy
topics:
  - Metrics
  - Thresholds
  - Imbalance
json: https://gurkanozkan.ai/api/learn/coding/mle-f1-maximising-threshold-17.json
robots: noindex
---

# F1-maximising threshold

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

```python
def best_f1_threshold(y_true: list[int], scores: list[float]) -> tuple[float, float]: ...
```

## Examples

Each call and the value it should give.

```python
>>> 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))
True
```

## Hints

1. Sweep candidate thresholds over the scores; compute F1 at each.
2. F1 = 2 * precision * recall / (precision + recall).
3. Keep the best (threshold-tie rule from the reference); return (best_f1, best_threshold).

## Reference solution

```python
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 best
```

## What 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).
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
