Pick the decision threshold that maximises F1

Why it matters Fraud, spam and moderation systems tune thresholds on validation data, and maximising F1 is a common default when precision and recall matter equally.

The default 0.5 threshold is rarely best. Sweeping thresholds and maximising F1 is a common way to choose one on a validation set.

Write best_f1_threshold(y, scores). y is 0/1, scores are floats. Try every distinct score t as a threshold, predicting positive when score >= t. F1 = 2 TP / (2 TP + FP + FN), with F1 = 0 when the denominator is 0. Return (t, f1) as floats for the best F1; on ties return the largest threshold.

Signaturedef best_f1_threshold(y, scores)

Example

y [0, 1, 1, 0, 1], scores [0.2, 0.9, 0.4, 0.5, 0.3] gives (0.3, 0.857143).

Understand the idea

A model outputs a score; you turn it into yes or no with a threshold. Move the threshold down and you catch more positives (recall up) but also flag more negatives (precision down). F1, the harmonic mean of precision and recall, balances the two, and the best threshold is usually not 0.5.

Worked example: labels 0, 1, 1, 0, 1 with scores 0.2, 0.9, 0.4, 0.5, 0.3. At t = 0.9 we flag one item, a true positive: TP 1, FP 0, FN 2, F1 = 2 / 5 = 0.4. At t = 0.4 we flag 0.9, 0.5 and 0.4: TP 2, FP 1, FN 1, F1 = 4 / 6 = 0.667. At t = 0.3 we add one more positive: TP 3, FP 1, FN 0, F1 = 6 / 7 = 0.857, the best.

Rule: F1(t) = 2 TP / (2 TP + FP + FN) with prediction score >= t; pick t with the largest F1.

Always choose the threshold on validation data and then freeze it for the test set and production.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplebest_f1_threshold([0, 1, 1, 0, 1], [0.2, 0.9, 0.4, 0.5, 0.3])
  • Sample 2: tie prefers larger thresholdbest_f1_threshold([1, 0, 1, 0], [0.9, 0.8, 0.7, 0.1])
  • Test 3: tied scoresbest_f1_threshold([1, 1, 0, 0, 1, 0], [0.6, 0.6, 0.6, 0.2, 0.9, 0.1])
  • Test 4: randombest_f1_threshold(_y, _s)