Sub topic 6
From scores to predictions: argmax and thresholds
A model does not output a prediction. It outputs scores, and a decision rule turns those scores into class labels. This chapter covers the two standard rules, argmax for multiclass and thresholds for multilabel. It also covers the edge cases where each one breaks.
It assumes you know binary logistic regression, precision, recall and F1, and basic NumPy. It also assumes you have seen softmax and sigmoid outputs, which earlier chapters cover.
Scores, probabilities and decisions
A classifier produces three kinds of numbers on the way to a prediction.
- Logits are raw scores, one per class or label. They can be any real number.
- Probabilities come from squashing logits. Softmax makes the K scores compete and sum to 1. Sigmoid squashes each score independently into (0, 1).
- Predictions are the final class indices or 0/1 indicators.
The decision rule is the last step, and it must match the output type. Softmax outputs pair with argmax, and sigmoid outputs pair with thresholds.
Argmax for multiclass
Argmax picks the index of the largest value in each row. Because softmax is monotonic, the largest logit is also the largest probability. You can take argmax of logits and skip the softmax when you only need the class. You need softmax only when you want probabilities for confidence, calibration or loss.
import numpy as np
proba = np.array([
[0.70, 0.20, 0.10],
[0.40, 0.35, 0.25],
[0.34, 0.33, 0.33],
[0.40, 0.40, 0.20],
])
confidence = proba.max(axis=1)
pred = proba.argmax(axis=1)
print("prediction:", pred)
print("confidence:", confidence)The prediction is [0 0 0 0], but the four rows are not equally trustworthy. Row 2 wins with 0.34 against 0.33, which is almost a coin flip. Row 3 is a tie, and argmax silently returns the first index. Argmax always returns an answer, however weak the evidence.
Rejecting low-confidence predictions
When a wrong answer costs more than no answer, add a reject option. Predict the argmax class only if the top probability clears a cutoff, and send the rest to a human or a fallback.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=0
)
clf = LogisticRegression(max_iter=1000).fit(X_train, y_train)
proba = clf.predict_proba(X_test)
pred = clf.classes_[proba.argmax(axis=1)]
confidence = proba.max(axis=1)
assert (pred == clf.predict(X_test)).all()
for cutoff in (0.0, 0.6, 0.9):
accepted = confidence >= cutoff
coverage = accepted.mean()
accuracy = (pred[accepted] == y_test[accepted]).mean()
print(f"cutoff {cutoff:.1f}: coverage {coverage:.2f}, "
f"accuracy on accepted {accuracy:.2f}")Raising the cutoff lowers coverage, the share of inputs you answer. Accuracy on the accepted inputs usually rises. This only works if the probabilities are meaningful, which is why calibration, covered in a later chapter, matters here.
Other argmax variants
- Top-k prediction. Return the k highest-scoring classes. This suits search and recommendation, where the right answer only needs to appear in a short list.
- Weighted argmax. Multiply each probability by a per-class weight before taking argmax. A larger weight makes the model favor that class when scores are close. This shifts the decision toward a costly class, such as a rare disease.
- Tie handling.
np.argmaxreturns the first maximum. If ties matter, break them explicitly, for example by class prior.
Thresholds for multilabel
In a multilabel problem each label is its own yes/no question. The rule is: predict label j when its probability reaches threshold t.
For a sigmoid, a threshold of 0.5 equals a logit of 0. You can threshold raw scores at 0, or probabilities at 0.5, and get the same result.
import numpy as np
proba = np.array([
[0.91, 0.62, 0.05, 0.10],
[0.45, 0.30, 0.20, 0.10],
[0.55, 0.52, 0.51, 0.49],
])
pred = (proba >= 0.5).astype(int)
print(pred)
print("labels per row:", pred.sum(axis=1))The output has [1 1 0 0], [0 0 0 0] and [1 1 1 0]. Three things can happen:
- The row predicts several labels, as rows 0 and 2 do. This is allowed.
- The row predicts no labels, as row 1 does. Whether that is allowed depends on your data.
- The row sits close to the cutoff on several labels, as row 2 does. Small shifts in the model change its output a lot.
Forcing at least one label
If every training example has at least one label, an empty prediction is almost certainly wrong. A common fix is to fall back to the single highest-scoring label for empty rows.
import numpy as np
proba = np.array([
[0.91, 0.62, 0.05, 0.10],
[0.45, 0.30, 0.20, 0.10],
[0.55, 0.52, 0.51, 0.49],
])
pred = (proba >= 0.5).astype(int)
empty = pred.sum(axis=1) == 0
pred[empty, proba[empty].argmax(axis=1)] = 1
print(pred)Row 1 now predicts label 0. Check your training data first. If empty label sets are legitimate, for example an image with none of the tags, this fallback creates false positives.
Global versus per-label thresholds
A single cutoff of 0.5 assumes every label has a similar base rate and similar model behavior. That is rarely true. A rare label has few positive training examples, so the model rarely pushes its probability above 0.5, and recall for that label drops. A frequent label can have the opposite problem.
Per-label thresholds fix this. Store one cutoff per label as a vector. NumPy broadcasting compares each column with its own cutoff.
import numpy as np
proba = np.array([
[0.91, 0.62, 0.05, 0.10],
[0.45, 0.30, 0.20, 0.10],
[0.55, 0.52, 0.51, 0.49],
])
thresholds = np.array([0.50, 0.25, 0.50, 0.50])
pred = (proba >= thresholds).astype(int)
print(pred)Label 1 has a lower cutoff of 0.25, so row 1 now predicts it. The shape of thresholds is (n_labels,), and it broadcasts across rows.
Choose cutoffs on a validation set, never on the test set. Tuning on the test set leaks information and inflates your scores. A later chapter covers the tuning procedure.
| Rule | Output | Typical use | Main risk |
|---|---|---|---|
| Argmax | Exactly one class | Multiclass | Always answers, even when unsure |
| Argmax with reject | One class or abstain | Costly errors | Coverage drops as the cutoff rises |
| Top-k | k ranked classes | Search, recommendation | Fixed k may not fit every input |
| Global threshold | Any subset of labels | Multilabel baseline | Rare labels are under-predicted |
| Per-label thresholds | Any subset of labels | Multilabel with imbalance | Overfits if tuned on little data |
| Top-k labels | Exactly k labels | Known label count | Wrong when the true count varies |
Common errors
- Softmax on a multilabel problem. Softmax forces probabilities to sum to 1, so labels compete. A row with two true labels can show at most about 0.5 each, and a 0.5 threshold then misses them.
- Thresholding softmax output in a multiclass problem. With many classes the top probability may be below 0.5, so you get an empty prediction. Use argmax.
- Argmax on a multilabel problem. This returns one label and discards the rest.
- Reading probabilities as confidence without checking calibration. A reported 0.9 may be right only 70% of the time. Reject cutoffs and thresholds inherit that error.
- Changing the threshold and expecting the model to change. The threshold moves only the decision. It trades precision for recall and does not make the underlying scores better.
Where the choice shows up in metrics
The decision rule changes the metric, even with the same model. Lowering a threshold raises recall and usually lowers precision. Metrics that need hard predictions, such as F1 and Hamming loss, move with the threshold. Ranking metrics that use raw scores do not.
That is why you compare models at tuned thresholds. A comparison at a fixed 0.5 can favor the model whose probabilities happen to sit near that cutoff.
Exercise
A multilabel model outputs sigmoid probabilities. For one input they are [0.40, 0.35, 0.10], and every training example has at least one label. (a) What does a global threshold of 0.5 predict? (b) What does the "force at least one label" rule predict? (c) Label 1 is rare and you lower its cutoff to 0.30. What is the prediction now, with the other cutoffs at 0.5?
Show answer
(a) [0, 0, 0], an empty set. (b) [1, 0, 0], because label 0 has the highest probability and becomes the fallback label. (c) [0, 1, 0], because 0.35 is at least 0.30 and the other two scores are below 0.5. The fallback rule no longer applies because the row is not empty.