Sub topic 8
Multilabel problem transformation methods
This chapter assumes you know binary logistic regression, train/test splits, and precision, recall and F1 for a binary problem. It also assumes you know how a multilabel target is stored as a multi-hot matrix and how a per-label sigmoid produces independent probabilities. Basic Python and NumPy are enough for the code.
The idea: turn one hard problem into easy ones
Most classifiers only predict one binary or one multiclass target. A multilabel target is a matrix Y with shape (n_samples, n_labels). A problem transformation method rewrites that matrix into one or more targets that an ordinary classifier can handle. You then map the predictions back into a label matrix.
Three methods cover most practical work:
| Method | Rewritten problem | Models trained | Uses label dependence |
|---|---|---|---|
| Binary relevance | One binary problem per label | L | No |
| Classifier chain | One binary problem per label, with earlier labels as extra features | L | Yes, in one direction |
| Label powerset | One multiclass problem, where each distinct label combination is a class | 1 | Yes, fully |
Here L is the number of labels.
Binary relevance
Binary relevance trains one binary classifier per label. Each classifier sees the full feature matrix X and one column of Y, and it treats every other label as if it did not exist. At prediction time you run all L classifiers and stack their outputs.
In scikit-learn, OneVsRestClassifier does this when you pass it a multi-hot matrix. It is the same class used for multiclass one-vs-rest, but it switches to multilabel behavior when Y has more than one column.
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
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)
# Binary relevance: one independent logistic regression per label.
model = OneVsRestClassifier(LogisticRegression(max_iter=1000)).fit(X_train, Y_train)
proba = model.predict_proba(X_test) # shape (n_samples, n_labels)
for threshold in (0.3, 0.5):
Y_pred = (proba >= threshold).astype(int)
print("threshold", threshold)
print(" subset accuracy:", round(accuracy_score(Y_test, Y_pred), 3))
print(" Hamming loss: ", round(hamming_loss(Y_test, Y_pred), 3))
print(" micro F1: ", round(f1_score(Y_test, Y_pred, average="micro", zero_division=0), 3))
print(" macro F1: ", round(f1_score(Y_test, Y_pred, average="macro", zero_division=0), 3))The code applies a threshold to the probabilities itself instead of calling model.predict. This keeps the decision rule visible and lets you change it without retraining. Lower thresholds usually raise recall and lower precision, so the two thresholds can give quite different F1 scores.
Strengths of binary relevance:
- It is simple, and training scales linearly with L.
- You can train the models in parallel, tune each one separately, and add or drop a label without touching the others.
- Each model gives a probability per label, which supports per-label thresholds.
Weaknesses:
- It ignores label dependence. If "beach" and "sea" almost always appear together, each model learns this only through the features, not from the other label.
- It can predict combinations that never occur in the data, because each label is decided alone.
- Rare labels get a heavily imbalanced binary problem, because most rows are negative for them.
Classifier chains
A classifier chain keeps the one-model-per-label structure but orders the labels. Model 1 predicts label 1 from X. Model 2 predicts label 2 from X plus label 1. Model k sees X plus the first k−1 labels. This lets later models use the answers of earlier ones, so the chain can represent dependence between labels.
from sklearn.datasets import make_multilabel_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.multioutput import ClassifierChain
from sklearn.metrics import f1_score
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)
chain = ClassifierChain(
LogisticRegression(max_iter=1000), order="random", random_state=0
).fit(X_train, Y_train)
Y_pred = chain.predict(X_test)
print("chain micro F1:", round(f1_score(Y_test, Y_pred, average="micro", zero_division=0), 3))Two details matter in practice:
- Training and prediction differ. During training, each model receives the true earlier labels. During prediction, it receives the predicted earlier labels, so one early mistake can pass down the chain. Scikit-learn's
ClassifierChainfollows this scheme. - Order matters. The result depends on the label order, and no order is best in general. Setting
order="random"removes one arbitrary choice, but the score still varies with the seed. A common remedy is to train several chains with different random orders and average their probabilities. Scikit-learn does not provide this as one class, so you write the loop yourself.
Chains also cost more than binary relevance. They cannot be trained in parallel across labels, and the L models depend on each other, so you cannot retrain one label in isolation.
Label powerset
Label powerset treats each distinct row of Y as a single class. If the training data contains the combinations {}, {A}, {A, B} and {B, C}, you get a four-class multiclass problem. A multiclass classifier then predicts one combination, and you decode it back to a multi-hot row.
Scikit-learn has no built-in class for this, but the transformation is short. np.unique with axis=0 finds the distinct rows and numbers them.
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.metrics import accuracy_score, hamming_loss, f1_score
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)
# Each distinct row of Y becomes one class index.
combos, y_class = np.unique(Y_train, axis=0, return_inverse=True)
y_class = y_class.ravel()
print("distinct label combinations in training data:", len(combos))
clf = LogisticRegression(max_iter=1000).fit(X_train, y_class)
# Predict a class index, then decode it back to a multi-hot row.
Y_pred = combos[clf.predict(X_test)]
print("subset accuracy:", round(accuracy_score(Y_test, Y_pred), 3))
print("Hamming loss: ", round(hamming_loss(Y_test, Y_pred), 3))
print("micro F1: ", round(f1_score(Y_test, Y_pred, average="micro", zero_division=0), 3))Strengths of label powerset:
- It models label dependence completely, because the classifier sees each full combination as one outcome.
- It only predicts combinations seen in training, so it never produces an implausible one.
- It trains a single model.
Weaknesses:
- The number of classes can grow toward
min(n_samples, 2^L). With 5 labels the limit is 32 classes. With 50 labels the number of observed combinations can approach the number of rows. - Many combinations have only one or two examples, so the classifier has little to learn from.
- It cannot predict a combination absent from the training set, even when the test row clearly calls for it.
- It gives one probability per combination, not one per label, so per-label thresholds need extra work. You can sum the probabilities of the combinations that contain a label to recover a marginal probability.
A pruned variant keeps only combinations that appear at least some minimum number of times and reassigns or drops the rest. This keeps the class count manageable.
Choosing a method
Use these criteria in order:
- Start with binary relevance. It is the baseline every other method must beat, and its per-label probabilities make threshold tuning easy.
- Try a classifier chain when labels depend on each other and you have enough data to benefit. Check by comparing it with the baseline on the same split. If the gain is within the variation you see across random chain orders, keep the simpler model.
- Try label powerset when L is small and label combinations repeat. Count distinct combinations first. If most appear only once, the method will struggle.
- Count the cost. Binary relevance and chains train L models. Label powerset trains one model with many classes.
Also check whether your base estimator already handles multilabel targets natively. Random forests, k-nearest neighbors and MLPClassifier in scikit-learn accept a multi-hot Y directly. Those models do not need a wrapper, and they may share structure across labels.
Exercise
A multilabel dataset has 40 labels and 10,000 rows. You count the distinct label combinations and find 6,500. Which of the three transformation methods is the weakest fit, and why?
Show answer
Label powerset. It would create about 6,500 classes for 10,000 rows, so most classes have one or two examples and the classifier cannot learn them reliably. It also cannot predict any combination missing from the training data. Binary relevance (40 models) or a classifier chain is a better starting point.
Exercise
In a classifier chain, what does model 3 receive as input during training, and what does it receive during prediction?
Show answer
During training, model 3 receives the features X plus the true values of labels 1 and 2 (in chain order). During prediction, it receives X plus the predicted values of labels 1 and 2 from models 1 and 2, so errors from earlier models can carry forward.