TExcelTAD
Home › Data Preparation Toolkit: Cleaning to Leakage-Free Splits › Threshold Adjustment and the Training-Data-Only Rule

Threshold Adjustment and the Training-Data-Only Rule

A classifier that outputs probabilities turns them into labels with a threshold: predict the positive class when the predicted probability is at least 0.5. Nothing about 0.5 is special. It is the right cut only when both kinds of error cost the same and the training data has the real class ratio, and on an imbalanced problem neither is usually true. Moving the threshold is the eighth imbalance remedy and often the simplest: no resampling, no weights, the same trained model, a different cut. This lesson shows how to choose it honestly, then states the rule that ties all eight remedies together: only the training data is ever rebalanced.

One model, many thresholds

Lowering the threshold flags more rows: recall goes up, precision goes down. The lab shows 1,000 scores, 10% of them positives, and a threshold you can slide. Note that the threshold here is on a score scale, not a probability; the trade is the same.

05010005scorecountScores by true classpositive →← negativenegativepositivepredicted +predicted −actual posactual neg52TP48FN21FP879TNprecision 0.712 recall 0.520 F1 0.6010.00.51.00.00.51.0false positive rateTPRROC curveAUC 0.921- - chance0.00.51.00.00.51.0recallprecisionPrecision-recallAP 0.664- - chance

At threshold 2 the model catches 52% of the positives with precision 0.712. Slide it down to 1 and recall rises to 0.850 while precision falls to 0.353, and accuracy drops from 0.931 to 0.829. The ROC AUC stays 0.921 at every threshold: the model is the same, only the cut moved.

In code, the threshold is picked on a validation set and then checked once on a test set that played no part in the choice.

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_curve, recall_score, precision_score

X, y = make_classification(n_samples=6000, n_features=8, n_informative=4, n_redundant=0,
                           n_clusters_per_class=1, weights=[0.96], flip_y=0.01,
                           class_sep=1.4, random_state=3)
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=1/3, stratify=y_tmp, random_state=0)
print("rows train/val/test:", len(y_tr), len(y_va), len(y_te), " positives:", int(y_tr.sum()), int(y_va.sum()), int(y_te.sum()))

model = LogisticRegression(max_iter=1000).fit(X_tr, y_tr)
p_va = model.predict_proba(X_va)[:, 1]
prec, rec, thr = precision_recall_curve(y_va, p_va)

# Goal from the business: catch at least 80% of positives, with the best precision possible.
ok = rec[:-1] >= 0.80
best = np.argmax(np.where(ok, prec[:-1], -1))
t = thr[best]
print(f"chosen on validation: threshold={t:.3f}  recall={rec[best]:.3f}  precision={prec[best]:.3f}")

p_te = model.predict_proba(X_te)[:, 1]
for name, cut in [("default 0.5", 0.5), ("tuned", t)]:
    pred = (p_te >= cut).astype(int)
    print(f"test, {name:<11} recall={recall_score(y_te, pred):.3f}  precision={precision_score(y_te, pred):.3f}")
rows train/val/test: 3000 1500 1500  positives: 133 67 66
chosen on validation: threshold=0.106  recall=0.806  precision=0.355
test, default 0.5 recall=0.424  precision=0.718
test, tuned       recall=0.742  precision=0.419

The validation set says a threshold of 0.106 reaches the recall goal (0.806) with precision 0.355. On the untouched test set the default cut of 0.5 finds only 42% of the positives; the tuned cut finds 74%, at precision 0.419. Two things to notice. First, the test recall (0.742) is below the 0.806 seen on validation: a threshold chosen on 67 validation positives is itself an estimate, and it is slightly optimistic for the data it was chosen on. Second, with only 66 test positives each one moves recall by 1.5 percentage points, so report such numbers with their counts.

Choosing the threshold with cross-validation

Holding out a validation set costs data. scikit-learn's TunedThresholdClassifierCV (new in version 1.5) runs cross-validation on the training data, finds the threshold that maximises a chosen score in each fold, and refits the model on all of it. FixedThresholdClassifier wraps a model with a threshold you already know.

python · try it yourself
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split, TunedThresholdClassifierCV
from sklearn.metrics import f1_score

X, y = make_classification(n_samples=6000, n_features=8, n_informative=4, n_redundant=0,
                           n_clusters_per_class=1, weights=[0.96], flip_y=0.01,
                           class_sep=1.4, random_state=3)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)

base = LogisticRegression(max_iter=1000).fit(X_tr, y_tr)
tuned = TunedThresholdClassifierCV(LogisticRegression(max_iter=1000), scoring="f1",
                                   cv=5, random_state=0).fit(X_tr, y_tr)
print(f"tuned threshold: {tuned.best_threshold_:.3f}  (CV F1 {tuned.best_score_:.3f})")
print(f"test F1 at 0.5:   {f1_score(y_te, base.predict(X_te)):.3f}")
print(f"test F1 at tuned: {f1_score(y_te, tuned.predict(X_te)):.3f}")
tuned threshold: 0.327  (CV F1 0.619)
test F1 at 0.5:   0.547
test F1 at tuned: 0.612

Cross-validated F1 picks a threshold of 0.327, and on the test set F1 improves from 0.547 to 0.612. The model's coefficients are the same as before; only the cut changed.

Tip: Optimise the business goal, not a habit. "Recall at least 0.8", "the best F1" and "the lowest expected cost" (a false negative costs 50, a false positive 2) give different thresholds. TunedThresholdClassifierCV accepts any scorer, including one built from a cost matrix with make_scorer.

The training-data-only rule

Every remedy in this section is fitted: a sampler decides which rows to copy or create, a weight is computed from class counts, a threshold is picked from scores. All of them follow the leakage rules:

  1. Split first. Rebalance only the training part (inside each cross-validation fold, with imblearn.pipeline.Pipeline).
  2. Validation and test sets keep the real class ratio, because that is the world the model will meet.
  3. Tune the threshold on validation data or by cross-validation, never on the test set.
  4. If deployment has a different class ratio than training (seasonal fraud, a new market), re-estimate it and adjust the threshold or recalibrate.

What breaks when the rule is ignored? Oversample the whole dataset first and then cross-validate a decision tree, which memorises its training rows: copies of the same minority row end up on both sides of every split.

python · try it yourself
from sklearn.datasets import make_classification
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import StratifiedKFold, cross_val_score
from imblearn.over_sampling import RandomOverSampler
from imblearn.pipeline import Pipeline

X, y = make_classification(n_samples=2000, n_features=8, n_informative=3, n_redundant=0,
                           weights=[0.95], flip_y=0.03, class_sep=0.6, random_state=7)
cv = StratifiedKFold(5, shuffle=True, random_state=0)
tree = DecisionTreeClassifier(random_state=0)

X_os, y_os = RandomOverSampler(random_state=0).fit_resample(X, y)   # WRONG: before the split
leaky = cross_val_score(tree, X_os, y_os, cv=cv, scoring="recall")
honest = cross_val_score(Pipeline([("os", RandomOverSampler(random_state=0)), ("tree", tree)]),
                         X, y, cv=cv, scoring="recall")
print(f"recall, oversampled before CV: {leaky.mean():.3f}")
print(f"recall, oversampled inside CV: {honest.mean():.3f}")
recall, oversampled before CV: 1.000
recall, oversampled inside CV: 0.328

Oversampling before cross-validation reports a perfect recall of 1.000: every minority row in a test fold has copies in the training folds, and the tree remembers them. Inside the pipeline, where each validation fold keeps only real, unseen rows, recall is 0.328. The second number is the one a deployed model would show.

Pitfalls

  • Tuning the threshold on the test set: the test score then measures how well you fitted the threshold to those rows, not how the model generalises.
  • Reporting a balanced test set: precision on a 50/50 test set says nothing about precision at a 1% positive rate.
  • Forgetting the threshold in production: model.predict uses 0.5. Ship the threshold with the model (a FixedThresholdClassifier or TunedThresholdClassifierCV object saves both together).
  • Stacking remedies: class weights plus oversampling plus a lowered threshold usually overshoot; tune one dial at a time.

Practice

  1. A spam filter must keep false positives (real mail in spam) below 1 per 1,000 legitimate emails. Which data do you use to set the threshold, and which metric drives the choice?
Answer

A validation set (or cross-validation on the training data) with the real ratio of spam to legitimate mail. Choose the lowest threshold whose false-positive rate on legitimate mail stays under 0.001, which gives the best recall allowed by that constraint. Then confirm it once on the test set.

  1. In the leaky example, why does the decision tree look so good?
Answer

After oversampling, each minority row exists many times. With shuffled folds, most test-fold minority rows have exact copies in the training folds, and an unpruned tree classifies an exact copy of a training row correctly. The score measures memorisation.

Test yourself

Which data should be used to choose a decision threshold?

  1. The test set
  2. Validation data or cross-validation on the training data
  3. The training predictions of the final model
  4. Any data, the threshold cannot leak

Lowering the threshold from 0.5 to 0.2 usually …

  1. raises precision and lowers recall
  2. raises recall and lowers precision
  3. changes neither
  4. changes the model's weights

What class ratio should the test set have?

  1. 50/50
  2. The real ratio the model will meet
  3. Whatever SMOTE produced
  4. Only minority rows

Why is oversampling before cross-validation wrong?

  1. It is slow
  2. Copies of the same row land in training and test folds, inflating the score
  3. It reduces recall
  4. It changes the number of features