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])]What the rule reports
Section titled “What the rule reports”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.
How to fix it
Section titled “How to fix it”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 is2 * 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 inpredict, so the threshold is not tuned on the rows that report the score.
Diagnostic message
Section titled “Diagnostic message”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.