Sub topic 12
Tuning thresholds per label
This chapter assumes you know how a per-label sigmoid produces probabilities, how binary relevance trains one model per label, and how precision, recall and F1 trade off in a binary problem.
Why 0.5 is a default, not a rule
A multilabel model outputs one probability per label. Turning each probability into a 0/1 prediction needs a threshold, and 0.5 is only a convention. It tends to fit poorly when:
- A label is rare. Its probabilities rarely reach 0.5, so recall is low.
- Your costs are uneven. A missed positive may hurt more than a false alarm.
- The model is not calibrated, so a score of 0.5 does not mean a 50% chance.
Lowering a threshold raises recall and usually lowers precision. Raising it does the reverse. Each label sits at a different point on that trade-off, so each label can get its own threshold.
The procedure
- Split the data into train, validation and test sets.
- Fit the model on the training set.
- Predict probabilities on the validation set.
- For each label, try a grid of thresholds and keep the one that maximizes the metric you care about, such as that label's F1.
- Freeze the thresholds, then report results once on the test set.
Worked example
import numpy as np
from sklearn.datasets import make_multilabel_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
from sklearn.metrics import f1_score
X, Y = make_multilabel_classification(
n_samples=2000, n_features=20, n_classes=5, n_labels=2, random_state=0
)
X_train, X_rest, Y_train, Y_rest = train_test_split(X, Y, test_size=0.4, random_state=0)
X_val, X_test, Y_val, Y_test = train_test_split(X_rest, Y_rest, test_size=0.5, random_state=0)
model = OneVsRestClassifier(LogisticRegression(max_iter=1000)).fit(X_train, Y_train)
proba_val = model.predict_proba(X_val)
proba_test = model.predict_proba(X_test)
grid = np.arange(0.05, 0.95, 0.05)
thresholds = np.zeros(Y_val.shape[1])
for j in range(Y_val.shape[1]):
scores = [
f1_score(Y_val[:, j], (proba_val[:, j] >= t).astype(int), zero_division=0)
for t in grid
]
thresholds[j] = grid[int(np.argmax(scores))]
print("per-label thresholds:", thresholds.round(2))
for name, t in (("global 0.5", 0.5), ("per-label", thresholds)):
Y_pred = (proba_test >= t).astype(int) # t broadcasts across label columns
print(name,
"micro F1:", round(f1_score(Y_test, Y_pred, average="micro", zero_division=0), 3),
"macro F1:", round(f1_score(Y_test, Y_pred, average="macro", zero_division=0), 3))The comparison proba_test >= thresholds works because a vector of length K broadcasts across the columns of an (n_samples, K) array. Per-label tuning usually helps macro F1 more than micro F1, because macro F1 weights rare labels equally with common ones.
Common errors
- Tuning on the test set. The chosen thresholds then overfit the test data, and the reported score is too optimistic. Tune on validation data or inside cross-validation.
- Tuning on very few positives. A label with a handful of validation positives gives a noisy best threshold. Use a coarser grid, pool cross-validated predictions, or fall back to a global threshold.
- Choosing the wrong objective. The best threshold for F1 differs from the best for recall at a fixed precision. Pick the metric from the application first.
- Forgetting to retune. Thresholds belong to a specific model. If you retrain, calibrate or change features, tune again.
Exercise
A rare label has probabilities that almost never exceed 0.5, so its recall is near zero at the default threshold. After tuning on validation data, its best threshold is 0.15. What happens to its precision and recall on the test set, and why must the 0.15 be chosen without looking at the test set?
Show answer
Recall rises because more examples now count as positive, and precision usually falls because some of the added predictions are false positives. F1 improves if the recall gain outweighs the precision loss. The threshold must come from validation data because picking it on the test set would fit it to that data, and the test score would overstate how the model performs on new data.