Skip to content

sklearn/manual-threshold-loop

Pack Severity Fix Versions
scikit-learn warning none, edit by hand All versions

A loop that scores one decision threshold per pass recomputes the metric for every threshold. precision_recall_curve and roc_curve sort the scores once and return the metric at every distinct threshold.

f1 = [f1_score(y, (proba >= t).astype(int)) for t in np.linspace(0, 1, 101)]
best = thresholds[np.argmax(f1)]
precision, recall, thresholds = precision_recall_curve(y, proba)
f1 = 2 * precision * recall / np.maximum(precision + recall, 1e-12)
best = thresholds[np.argmax(f1[:-1])]

The rule reports a for loop or a comprehension whose body compares scores with the loop name, as proba >= t or scores > t, and calls a classification metric such as f1_score, precision_score, recall_score, accuracy_score or confusion_matrix.

xpd has no automatic fix, so replace the loop by hand.

  • precision_recall_curve(y, scores) gives precision and recall at every threshold, and F1 is 2 * p * r / (p + r) on its output.
  • roc_curve(y, scores) gives the false and true positive rates at every threshold.
  • TunedThresholdClassifierCV(est, scoring="f1") chooses the threshold by cross-validation and applies it in predict, so the threshold is not tuned on the rows that report the score.
This scores one threshold $T per pass. precision_recall_curve(y, scores) or roc_curve(y, scores) returns the metric at every threshold in one sorted pass, with F1 as 2 * p * r / (p + r), and TunedThresholdClassifierCV(est, scoring=...) chooses the threshold by cross-validation and applies it in predict.

See all rules in the scikit-learn pack.