Multi-label learning: one example, several labels
多标签学习
Fit a transparent binary-relevance baseline and distinguish Hamming loss, subset accuracy, micro F1 and macro F1.
multi-label-learningOne photo can need several tags
A photograph may show both a bicycle and a person. Forcing exactly one category throws away information. Multi-label classification predicts a set of applicable labels, represented as a binary vector. Multi-class classification instead chooses one label from mutually exclusive alternatives.
With L labels there are 2ᴸ possible subsets, including the empty set. A model need not enumerate all of them: binary relevance trains one binary predictor per label. Zhang and Zhou’s review, SectionsII andIII-B.1, defines the setting and this baseline. We will use a deliberately small constant predictor to make its fitted probabilities and evaluation completely inspectable. Read Bernoulli models first.
Choose what counts as a mistake
Let yᵢ,ŷᵢ be binary vectors for N examples and L labels. Two common measures are:
Hamming loss counts individual label errors; subset accuracy requires the entire predicted set to match. Neither can replace the other without changing the evaluation goal. “Accuracy” alone is therefore an incomplete metric name.
For equal-cost Hamming loss, predicting label j as 1 has conditional risk 1−pⱼ; predicting 0 has risk pⱼ. Thus thresholding the true marginal probability at 1/2 is optimal, with either decision allowed at equality. This argument does not require labels to be conditionally independent. But predicting the most likely whole set requires the joint distribution.
For example, suppose two-label sets 00,11,10 have probabilities 0.40,0.35,0.25. Marginals are(0.60,0.35), so marginal thresholding predicts 10. The most likely complete set is 00. The different predictions optimize different losses.
Fit a minimal binary-relevance baseline
Our model ignores input features and estimates each label prevalence from training data. A symmetric Beta(α,α) prior gives posterior mean:
This follows by multiplying the Bernoulli likelihood by the Beta prior, obtaining Beta(cⱼ+α,N_train−cⱼ+α). With six training rows, counts(3,3,1) and α=1, probabilities are(1/2,1/2,1/4). Our explicit tie rule includes a label when p≥1/2, so every test example receives 110. The scores do not sum to one, because the labels are not mutually exclusive.
Feature-dependent binary relevance can use logistic regressions or other classifiers instead. An independent-head architecture does not automatically imply that real labels are independent; multiplying its marginal probabilities into a joint model would add that modeling assumption.
Fit on training labels, evaluate on a separate table
The complete Python 3.12 program fits the constant model and evaluates four separate synthetic test records:110,100,001,000. It also executes an all-negative baseline. Neither test labels nor test metrics affect fitting or the threshold.
from fractions import Fraction as F
def binary_matrix(rows):
rows=[list(row) for row in rows]
if not 1<=len(rows)<=64 or not 1<=len(rows[0])<=16 or any(len(row)!=len(rows[0]) for row in rows):
raise ValueError('a nonempty binary matrix with at most64 rows and16 labels required')
if any(type(v) is not int or v not in (0,1) for row in rows for v in row):
raise ValueError('integer zero/one labels required; missing labels are not negatives')
return rows
def fit_constant_relevance(labels, alpha=1):
labels=binary_matrix(labels);n=len(labels);width=len(labels[0])
if type(alpha) not in (int,F) or not 0<alpha<=1000:
raise ValueError('positive rational smoothing at most1000 required')
alpha=F(alpha)
return [(sum(row[j] for row in labels)+alpha)/(n+2*alpha) for j in range(width)]
def predict_constant(probabilities, count, threshold=F(1,2)):
probabilities=list(probabilities)
if not 1<=len(probabilities)<=16 or any(type(p) not in (int,F) or not 0<=p<=1 for p in probabilities):
raise ValueError('bounded rational label probabilities required')
if type(count) is not int or not 1<=count<=64 or type(threshold) not in (int,F) or not 0<=threshold<=1:
raise ValueError('bounded count and rational threshold required')
return [[int(p>=threshold) for p in probabilities] for _ in range(count)]
def metrics(truth, prediction):
truth=binary_matrix(truth);prediction=binary_matrix(prediction)
if len(truth)!=len(prediction) or len(truth[0])!=len(prediction[0]):raise ValueError('matching matrices required')
n=len(truth);width=len(truth[0]);counts=[]
for j in range(width):
tp=sum(a[j]==1 and b[j]==1 for a,b in zip(truth,prediction))
fp=sum(a[j]==0 and b[j]==1 for a,b in zip(truth,prediction))
fn=sum(a[j]==1 and b[j]==0 for a,b in zip(truth,prediction));counts.append((tp,fp,fn))
def f1(tp,fp,fn):return F(2*tp,2*tp+fp+fn) if 2*tp+fp+fn else F(0)
totals=[sum(row[j] for row in counts) for j in range(3)]
return dict(hamming=F(totals[1]+totals[2],n*width),
subset_accuracy=F(sum(a==b for a,b in zip(truth,prediction)),n),
micro_f1=f1(*totals),macro_f1=sum((f1(*row) for row in counts),F(0))/width)
if __name__=='__main__':
train=[[1,1,0],[1,1,0],[1,0,0],[0,1,0],[0,0,1],[0,0,0]]
test=[[1,1,0],[1,0,0],[0,0,1],[0,0,0]]
p=fit_constant_relevance(train);pred=predict_constant(p,len(test))
print('fitted probabilities:',*[str(v) for v in p]);print('predicted label vector:',pred[0])
for name,guess in [('fitted constant model',pred),('all-negative baseline',[[0]*3 for _ in test])]:
print(name)
for key,value in metrics(test,guess).items():print(key,value)
Output:
fitted probabilities: 1/2 1/2 1/4
predicted label vector: [1, 1, 0]
fitted constant model
hamming 1/2
subset_accuracy 1/4
micro_f1 1/2
macro_f1 16/45
all-negative baseline
hamming 1/3
subset_accuracy 1/4
micro_f1 0
macro_f1 0
There are 12 test label decisions. The fitted model makes five false positives and one false negative, giving Hamming loss 1/2. Only the first entire label set matches, giving subset accuracy 1/4. The all-negative baseline makes four label errors, so it wins on Hamming loss while failing to retrieve any positive labels.
The code uses exact fractions, up to 64 rows and 16 labels. Fitting and evaluation cost O(NL); the constant model stores O(L) values. It validates rectangular binary input. Missing labels must be modeled or masked separately; passing zero would assert a known negative.
Micro and macro averaging answer different questions
For each label, count true positives TP, false positives FP and false negatives FN. Then:
Micro averaging pools counts before taking a ratio; macro averaging gives each label’s F 1 equal weight. The example yields micro F 1=1/2 and macro F 1=16/45. A label with no positives in either truth or prediction has an undefined 0/0 expression; our implementation assigns it F 1=0 and includes it in the macro average. This convention is explicit, not an algebraic identity. The fixed scikit-learn 1.7 F 1 documentation documents averaging and zero-division choices.
A single threshold need not optimize F 1, asymmetric error costs or all labels equally. Select thresholds with training/validation data, then keep them fixed for test evaluation. Rare labels need per-label reporting; a high score dominated by absent labels can hide complete failure on the labels users care about.
The constant model learns only prevalence. Classifier chains, label-set models and shared representations can use dependencies or input features, but introduce their own estimation and inference costs. An empty label set may be valid; forcing at least one label is a task-specific policy, not a universal requirement.
Name the metric before declaring a winner
- Why are probabilities not passed through one softmax here?
Answer 1: Several labels may apply simultaneously; their marginal probabilities need not sum to one.
- How many test label decisions are wrong for the fitted constant model?
Answer 2: Six of twelve: five false positives and one false negative.
- Does optimal Hamming prediction require label independence?
Answer 3: No. Its additive risk depends on the marginal probabilities; whole-set prediction can require joint dependence.
- Why can the all-negative baseline win on Hamming loss but have zero F 1?
Answer 4: Many label decisions are negative, while the baseline finds no true positives.
Expand the baseline without changing the test
Project: replace the constant probabilities with one feature-dependent logistic model per label. Tune per-label thresholds on validation data, then report Hamming loss, subset accuracy, micro/macro F 1 and label support on a fixed test set. Add a label that never appears and state how its undefined F 1 is handled.
Compare a classifier chain with binary relevance at the same feature and data budget. Keep the distinction between learning label correlations and choosing a metric visible. Multi-task learning can share representations across outputs, but sharing alone does not settle how label-set predictions should be evaluated.
Make a prediction, then check
Does Hamming-optimal marginal thresholding require independent labels?
Learning objectives
- Distinguish label marginals from complete label-set predictions.
- Fit a smoothed per-label prevalence baseline.
- Compute and interpret micro/macro metrics with explicit zero rules.
Prerequisites & connections
Explore related knowledge →References
- A Review on Multi-Label Learning Algorithms — author manuscript
Min-Ling Zhang; Zhi-Hua Zhou · 2014 - f1_score — scikit-learn1.7 documentation
scikit-learn developers
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Exact rational metrics, four-outcome task risks, source/frozen/gradient fits and shifted-domain risks are checked against literal or analytic references. No external runtime dependencies.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- A Review on Multi-Label Learning Algorithms — author manuscript · Author manuscript42pages, SectionsII-A/II-B andIII-B.1: sets of labels, thresholds, Hamming/subset metrics and binary relevance. Journal citation26(8):1819–1837,2014 distinguished from earlier manuscript/online version; no forced nonempty output rule adopted.
- f1_score — scikit-learn1.7 documentation · Fixed1.7 page rendered1.7.2: micro pools counts, macro averages per-labelF1, zero_division options. Used as metric reference; runtime implementation is original standard-library fractions.
Related topics