Sub topic 12
Tuning thresholds per label
This chapter assumes you can train a multilabel model that outputs one probability per label, as in the binary relevance chapter. It also assumes you know precision, recall and F1 for a single binary problem, and that you are comfortable with NumPy broadcasting.
Why 0.5 is a default, not a decision
A multilabel model gives each label a score, and you must turn each score into a yes or no. The usual rule is "predict the label if the probability is at least 0.5". That number is a convention. It is the best choice only when the probabilities are well calibrated and a false positive costs the same as a false negative.
Those conditions rarely hold. A rare label, such as a tag that appears on 3% of documents, may almost never reach 0.5. The model can rank positive examples above negative ones and still never predict the label. Recall for that label is then close to zero, and macro F1 drops with it.
Tuning means choosing the cutoff on purpose, using data the model did not train on.
Three levels of threshold
| Strategy | Number of thresholds | Typical use |
|---|---|---|
| Fixed default | 1 (0.5) | Baseline, balanced labels, calibrated probabilities |
| Global threshold | 1 (tuned) | Labels have similar frequency and difficulty |
| Per-label thresholds | K, one per label | Labels differ in frequency or in the cost of errors |
A global threshold is a one-parameter search, so it is cheap and rarely overfits. Per-label thresholds fit K parameters. They adapt to each label, but each one is estimated from that label's positives only. A label with 15 validation positives gives a noisy estimate.
The procedure
Threshold tuning is a second fitting step, so it needs its own data. If you choose thresholds on the test set, the reported score is optimistic, because you picked the cutoffs that happen to look best on it.
flowchart TDReplace that stub with the real diagram below.
The steps are:
- Split off a test set and do not touch it.
- Split the remaining data into a fit part and a validation part.
- Fit the model on the fit part.
- Predict probabilities on the validation part.
- For each label, choose the threshold that maximizes your target metric on that column.
- Predict on the test set with those thresholds and score once.
Finding the best threshold for one label
The function precision_recall_curve evaluates every distinct score as a possible cutoff. It returns precision and recall arrays that are one element longer than the threshold array, because the last point corresponds to a cutoff above every score. Drop that last point before computing F1.
import numpy as np
from sklearn.datasets import make_multilabel_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score, precision_recall_curve
from sklearn.model_selection import train_test_split
from sklearn.multiclass import OneVsRestClassifier
X, Y = make_multilabel_classification(
n_samples=2000, n_features=20, n_classes=5, n_labels=2, random_state=0
)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.25, random_state=0)
X_fit, X_val, Y_fit, Y_val = train_test_split(
X_train, Y_train, test_size=0.25, random_state=1
)
model = OneVsRestClassifier(LogisticRegression(max_iter=1000)).fit(X_fit, Y_fit)
val_proba = model.predict_proba(X_val)
test_proba = model.predict_proba(X_test)
def best_threshold(y_true, scores, default=0.5):
"""Return the cutoff that maximizes F1 for one label."""
if y_true.sum() == 0:
return default # no positives: F1 is undefined, keep the default
precision, recall, thresholds = precision_recall_curve(y_true, scores)
p, r = precision[:-1], recall[:-1]
f1 = 2 * p * r / np.maximum(p + r, 1e-12)
return thresholds[np.argmax(f1)]
thresholds = np.array(
[best_threshold(Y_val[:, j], val_proba[:, j]) for j in range(Y_val.shape[1])]
)
print("per-label thresholds:", thresholds.round(3))
# Broadcasting compares column j of test_proba with thresholds[j].
pred_default = (test_proba >= 0.5).astype(int)
pred_tuned = (test_proba >= thresholds).astype(int)
for name, pred in (("0.5 everywhere", pred_default), ("per-label", pred_tuned)):
print(
name,
"micro F1:", round(f1_score(Y_test, pred, average="micro", zero_division=0), 3),
"macro F1:", round(f1_score(Y_test, pred, average="macro", zero_division=0), 3),
)The comparison line test_proba >= thresholds works because a (n_samples, K) array and a (K,) array broadcast along the last axis. Each column meets its own cutoff. If you build a (K, 1) array by mistake, you will compare the wrong axes or get a shape error.
Choosing what to optimize
The metric you maximize decides where the threshold lands.
- Maximizing F1 per label balances precision and recall for that label. It is the usual choice and pairs naturally with macro F1.
- Maximizing F-beta with beta above 1 favors recall. Use it when a missed label costs more than a spurious one, for example flagging content for human review.
- Fixing a minimum precision, then taking the lowest threshold that meets it, suits cases where false alarms are expensive.
- Maximizing micro F1 across all labels at once is a joint problem. A simple approximation tunes one global threshold on the flattened validation matrix.
Optimizing each label's F1 separately does not maximize micro F1 exactly. Micro F1 pools counts across labels, so frequent labels dominate it. Per-label tuning mostly lifts macro F1, and micro F1 may change little.
Common errors
Tuning on the test set. The test score then reflects the thresholds chosen to fit it. Keep a separate validation set, or use cross-validated out-of-fold probabilities (for example with cross_val_predict and method="predict_proba"), and tune on those.
Tuning on the training probabilities. A flexible model is overconfident on data it has seen. Thresholds chosen there will not transfer.
Trusting thresholds from few positives. A label with a handful of validation positives gives an unstable optimum, because the F1 curve is jagged. Options include pooling more data through cross-validation, smoothing by averaging thresholds across folds, or falling back to a global threshold for rare labels.
Ignoring ties and extreme values. The best F1 can sit at a threshold that is the score of a single example. Averaging per-fold thresholds is more robust than a single raw argmax.
Forgetting the empty prediction. After thresholding, some rows may have no label at all. Decide whether that is acceptable. If every item must have at least one label, set the highest-scoring label to 1 for empty rows.
empty = pred_tuned.sum(axis=1) == 0
pred_tuned[empty, test_proba[empty].argmax(axis=1)] = 1
print("rows fixed:", int(empty.sum()))Changing the model without retuning. Thresholds belong to a specific model and validation set. Retraining, resampling, or adding class weights changes the probability scale, so the thresholds must be recomputed.
Thresholds and calibration
Tuning a threshold shifts the cutoff. It does not change the probabilities. If you only need class decisions, tuning is enough. If you also report or use the probabilities, for example to rank items or to combine with costs, calibrate them separately. Because the tuned cutoff is chosen on ranked scores, a monotonic calibration step such as isotonic regression or Platt scaling leaves the achievable F1 unchanged. It changes only the numeric value of the best threshold.
Summary
Start with 0.5 as a baseline. Tune a global threshold if labels behave alike. Move to per-label thresholds when labels differ in frequency or cost. In every case, choose cutoffs on validation data, name the metric you are optimizing, and score the test set once.
Exercise
You tune a per-label threshold for each of 20 labels on a validation set, then report macro F1 on that same validation set and get 0.71. A colleague says the number is too high. Why, and what would you change?
Show answer
The thresholds were chosen to maximize F1 on the validation set, so the score on that set is optimistically biased. Report the score on a held-out test set that played no part in choosing thresholds, or use nested cross-validation where thresholds are tuned in inner folds and scored in outer folds.
Exercise
A label has only 8 positives in the validation set, and its tuned threshold is 0.91 while the other labels land near 0.3 to 0.5. Name two reasonable ways to handle it.
Show answer
Estimate the threshold from more data, for example by tuning on out-of-fold probabilities from cross-validation and averaging per-fold thresholds. Alternatively, fall back to a global or default threshold for that label, since an estimate based on 8 positives is unstable. Checking that the label's average precision is above its base rate is also reasonable.