LearnCoding

F1-maximising threshold

EasyMetrics, Thresholds, Imbalance

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

Solve it in your own editor; nothing on this page runs code.

Hints

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 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.