Sub topic 11
Evaluating multilabel models
This chapter assumes you can train a binary classifier, read precision, recall and F1, and have met micro and macro averaging in the multiclass setting. It covers how to score a model whose prediction is a set of labels, which metric answers which question, and the mistakes that make a multilabel model look better or worse than it is.
Why multiclass accuracy does not carry over
In multiclass classification each sample has one true class and one predicted class, so a prediction is either right or wrong. In multilabel classification the target is a row of K zeros and ones. A prediction can be fully right, fully wrong, or partly right. A metric has to say how partial credit is counted.
The metrics fall into three groups:
- Example-based metrics score each sample's label set, then average over samples. Subset accuracy, Hamming loss and samples-averaged F1 belong here.
- Label-based metrics score each label as its own binary problem, then average over labels. Micro, macro and weighted F1 belong here.
- Ranking metrics score the probabilities directly, before any threshold. ROC AUC and average precision belong here.
A worked example you can check by hand
Take three samples and three labels. The true targets and predictions are:
| Sample | True labels | Predicted labels |
|---|---|---|
| 1 | {0, 2} | {0} |
| 2 | {1} | {1} |
| 3 | {0, 1} | {0} |
The model never predicts label 2, and it misses label 1 for sample 3.
import numpy as np
from sklearn.metrics import (
accuracy_score, hamming_loss, f1_score, jaccard_score,
classification_report, multilabel_confusion_matrix,
)
Y_true = np.array([[1, 0, 1],
[0, 1, 0],
[1, 1, 0]])
Y_pred = np.array([[1, 0, 0],
[0, 1, 0],
[1, 0, 0]])
print("subset accuracy:", round(accuracy_score(Y_true, Y_pred), 3))
print("Hamming loss: ", round(hamming_loss(Y_true, Y_pred), 3))
for avg in ("micro", "macro", "weighted", "samples"):
score = f1_score(Y_true, Y_pred, average=avg, zero_division=0)
print(f"{avg:>8} F1:", round(score, 3))
print("samples Jaccard:", round(jaccard_score(Y_true, Y_pred, average="samples"), 3))
print(multilabel_confusion_matrix(Y_true, Y_pred))
print(classification_report(Y_true, Y_pred, zero_division=0))The printed values are subset accuracy 0.333, Hamming loss 0.222, micro F1 0.75, macro F1 0.556, weighted F1 0.667 and samples F1 0.778. The sections below derive each one.
Example-based metrics
Subset accuracy
Subset accuracy counts a sample as correct only if the entire label vector matches. In the example only sample 2 matches, so the score is 1/3. In sklearn, accuracy_score on a 2D indicator matrix computes this metric. It is not the per-label accuracy you might expect.
Subset accuracy is strict. With 50 labels, getting 49 right and one wrong scores zero for that sample. It is useful when a partly right answer is no use, for example when the label set triggers one downstream action. It is a poor choice for model comparison on large label spaces, because most scores end up near zero.
Hamming loss
Hamming loss is the fraction of individual label slots that are wrong, averaged over all samples and labels. In the example, 2 of 9 slots are wrong, giving 0.222. Lower is better, and 0 is perfect.
The weakness is sparsity. Most multilabel datasets have few positives per sample. If a sample has 3 positives among 100 labels, a model that predicts nothing has a Hamming loss of 0.03. That looks excellent, yet the model has learned nothing. Always compare Hamming loss with a baseline.
Samples-averaged F1 and Jaccard
Samples-averaged F1 computes precision, recall and F1 between the true set and the predicted set of each sample, then averages over samples.
- Sample 1: precision 1, recall 0.5, F1 0.667.
- Sample 2: F1 1.
- Sample 3: F1 0.667.
The mean is 0.778. This metric gives partial credit and suits tagging and recommendation tasks, where each item gets a set of tags. The Jaccard score is the overlap divided by the union of the two sets. It is stricter than F1 and ranks models in the same order in most cases.
A sample with no true labels and no predicted labels has an undefined F1. The zero_division argument decides whether it counts as 0 or 1. Set it explicitly and report it, because the choice changes the score on data where empty label sets are common.
Label-based metrics
Label-based metrics treat each column as a binary problem. multilabel_confusion_matrix returns one 2x2 matrix per label, laid out as [[TN, FP], [FN, TP]]. From these counts you get per-label precision, recall and F1. The averaging then works as in the multiclass chapter.
- Micro F1 pools the counts from every label first. Here TP is 3, FP is 0 and FN is 2, so precision is 1, recall is 0.6 and F1 is 0.75. Frequent labels dominate the result.
- Macro F1 averages the per-label F1 scores with equal weight. The three labels score 1, 0.667 and 0, so the mean is 0.556. Rare labels count as much as common ones, so one label the model never predicts pulls the score down sharply.
- Weighted F1 averages the per-label scores weighted by support, the number of true positives per label. The supports are 2, 2 and 1, so the result is (2×1 + 2×0.667 + 0×1)/5 = 0.667.
If micro F1 is far above macro F1, the model does well on common labels and badly on rare ones. Read the per-label rows of classification_report to find which ones.
Metrics depend on the threshold
Every metric above works on hard 0/1 predictions, so each one changes when the threshold changes. Lowering the threshold raises recall and lowers precision. The following code scores one model at two thresholds and compares it with an all-zeros baseline.
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 accuracy_score, hamming_loss, f1_score, average_precision_score
import numpy as np
X, Y = make_multilabel_classification(
n_samples=1000, 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, random_state=0)
model = OneVsRestClassifier(LogisticRegression(max_iter=1000)).fit(X_train, Y_train)
proba = model.predict_proba(X_test)
baseline = np.zeros_like(Y_test)
print("all-zeros Hamming:", round(hamming_loss(Y_test, baseline), 3))
print("macro average precision:", round(average_precision_score(Y_test, proba, average="macro"), 3))
for t in (0.3, 0.5):
pred = (proba >= t).astype(int)
print(t, "subset", round(accuracy_score(Y_test, pred), 3),
"hamming", round(hamming_loss(Y_test, pred), 3),
"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))average_precision_score takes probabilities, so it does not depend on the threshold. Use it, or ROC AUC, to judge ranking quality. Then use the F1 metrics to judge the model after you set thresholds. If AUC is high and F1 is low, the model ranks well and the thresholds are the likely problem.
Common errors
- Reading
accuracy_scoreas per-label accuracy. On a multilabel matrix it is subset accuracy. For per-label accuracy, use 1 minus the Hamming loss. - Using only micro F1. It hides failures on rare labels. Report macro F1 as well, and check the per-label report.
- Skipping the baseline. Compare every model with an all-zeros prediction and with one that predicts the most frequent labels.
- Tuning the threshold on the test set. Choose thresholds on validation data, then score the test set once.
- Leaving
zero_divisionat its default. Warnings appear when a label has no predicted or no true positives. Setzero_divisionand report the choice. - Using random splits on rare labels. A label can end up missing from the test set, which makes its F1 undefined. Use stratified or iterative-stratified splits, covered in a later chapter.
Exercise
A dataset has 200 labels, and each sample has on average 4 positive labels. A model that predicts all zeros has a Hamming loss of 0.02. Your model has a Hamming loss of 0.015 and a macro F1 of 0.05. Is it a good model?
Show answer
Probably not. The all-zeros baseline is 4/200 = 0.02, so a loss of 0.015 beats it by only a little. The macro F1 of 0.05 shows the model is nearly useless on most labels. Report macro F1 and per-label scores, and judge the model on those instead of on Hamming loss.
Exercise
For the worked example, change the prediction for sample 1 to {0, 2}. Which of the six scores (subset accuracy, Hamming loss, micro, macro, weighted and samples F1) change, and what is the new subset accuracy?
Show answer
All six change. Sample 1 now matches exactly, so subset accuracy becomes 2/3 and Hamming loss becomes 1/9 = 0.111. Label 2 now has TP = 1 and F1 = 1. Micro F1 becomes 0.857, macro F1 becomes 0.889 and weighted F1 becomes 0.867. Samples F1 becomes (1 + 1 + 0.667)/3 = 0.889.