Sub topic 14
Label dependence and co-occurrence
This chapter assumes you can fit a one-vs-rest multilabel model in scikit-learn. It also assumes you know the binary relevance, classifier chain and label powerset transformations from the previous chapters, and that you can read a multi-hot target matrix with shape (n_samples, n_labels).
What label dependence means
In a multilabel problem, labels often appear together. A news article tagged "politics" is more likely to be tagged "economy" than a random article is. This is co-occurrence: two labels appear on the same sample more often, or less often, than chance would predict.
Co-occurrence is not the same as label dependence, and the difference decides which model you need.
- Marginal dependence means label A and label B are statistically related when you ignore the features. Co-occurrence counts measure this.
- Conditional dependence means A and B are still related after you know the features
x. Formally,P(A, B | x)does not equalP(A | x) * P(B | x).
Binary relevance trains one independent model per label, so it estimates each P(label | x) separately. If the labels are only marginally dependent, the features already explain the pattern. A good binary relevance model reproduces it without any help. If the labels are conditionally dependent, binary relevance cannot represent the joint structure, and a chain or powerset model has something to gain.
A common error is to see a strong co-occurrence matrix and conclude that binary relevance will fail. It may not.
Measuring co-occurrence
Three numbers are useful. The raw count tells you how often two labels appear together. The conditional probability P(j | i) tells you how likely label j is given label i. The lift is P(i, j) / (P(i) * P(j)). A lift of 1 means independence, above 1 means attraction, and below 1 means repulsion.
import numpy as np
from sklearn.datasets import make_multilabel_classification
X, Y = make_multilabel_classification(
n_samples=1000, n_features=20, n_classes=5, n_labels=2, random_state=0
)
co = Y.T @ Y # co[i, j] = samples having both i and j
counts = np.diag(co) # samples having label i
cond = co / counts[:, None] # cond[i, j] = P(label j | label i)
p = counts / len(Y)
lift = (co / len(Y)) / np.outer(p, p)
print("counts:", counts)
print("P(j | i):")
print(cond.round(2))
print("lift (off-diagonal matters):")
print(lift.round(2))Read the matrices row by row. In cond, row i answers "given that label i is present, how often is each other label present?" The matrix is not symmetric, because P(j | i) and P(i | j) differ whenever the labels have different frequencies.
Lift is more honest than raw conditional probability for rare labels. A label present on 60% of all samples will show a high P(j | i) for every i, but its lift will sit near 1.
Marginal versus conditional dependence in practice
Co-occurrence only tells you about marginal dependence. To probe conditional dependence, fit binary relevance and look at the residuals. A residual is the true label minus the predicted probability. If the residuals of two labels are correlated on held-out data, the model is missing a shared signal that those labels have in common.
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.multiclass import OneVsRestClassifier
from sklearn.multioutput import ClassifierChain
from sklearn.metrics import accuracy_score, 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)
def report(name, Y_pred):
print(
f"{name:18s} subset acc {accuracy_score(Y_test, Y_pred):.3f} "
f"micro F1 {f1_score(Y_test, Y_pred, average='micro', zero_division=0):.3f}"
)
# Binary relevance
br = OneVsRestClassifier(LogisticRegression(max_iter=1000)).fit(X_train, Y_train)
proba = br.predict_proba(X_test)
report("binary relevance", (proba >= 0.5).astype(int))
# Residual correlation: dependence left over after using the features
resid = Y_test - proba
print("residual correlation:")
print(np.corrcoef(resid.T).round(2))
# Classifier chain
chain = ClassifierChain(
LogisticRegression(max_iter=1000), order="random", random_state=0
).fit(X_train, Y_train)
report("classifier chain", chain.predict(X_test))
# Label powerset: one multiclass problem over observed label combinations
combos, y_lp = np.unique(Y_train, axis=0, return_inverse=True)
lp = LogisticRegression(max_iter=1000).fit(X_train, y_lp.ravel())
report("label powerset", combos[lp.predict(X_test)])
print("distinct combinations in training data:", len(combos))Treat the numbers from one split as a rough guide only. Differences of a point or two between methods can come from the split rather than the method. Repeat the comparison over several splits, or use cross-validation, before you choose a model.
How each transformation handles dependence
The three transformations from the previous chapter differ in what they assume about label structure.
| Method | Dependence it can use | Main cost | Main risk |
|---|---|---|---|
| Binary relevance | None directly | `K` models | Predicts label sets that never occur |
| Classifier chain | Each label conditioned on earlier labels | `K` models, trained and applied in sequence | Results depend on label order, and early mistakes propagate |
| Label powerset | Full joint distribution | One model over up to `2^K` classes | Rare combinations have few examples, and unseen combinations can never be predicted |
The diagram shows where each method sees the other labels.
Chains depend on label order
In a chain, model B receives the prediction for A as an extra input. Modelling A first and B second is mathematically equivalent to modelling them in the other order, but in practice the fitted models differ. A poor order can make results worse than binary relevance.
Two approaches reduce the risk. You can order labels from the most frequent to the least frequent, or from easiest to hardest. You can also train several chains with random orders and average their probability outputs. scikit-learn's ClassifierChain supports order="random" with a random_state, so an ensemble is a loop over seeds.
Chains train on true labels and predict with estimated ones
During training, ClassifierChain feeds each model the true values of earlier labels. At prediction time, it feeds the predicted values. This mismatch is called exposure bias. When an early prediction is wrong, every later model receives an input it rarely saw in training. The error spreads down the chain. Chains therefore tend to help most when the early labels are predicted accurately.
Label powerset needs enough data per combination
Run np.unique(Y_train, axis=0) and count the combinations. With 5 labels the maximum is 32, which is manageable. With 100 labels the observed count may be in the thousands, and most combinations appear once or twice. A classifier cannot learn from one example. A model trained this way also cannot output a combination absent from the training data, even if that combination is correct for a test sample.
Choosing between methods
Use these checks in order.
- Check the metric you care about. Subset accuracy (exact match of the whole label set) rewards getting joint structure right. Micro F1 and Hamming loss mostly reward per-label accuracy. Binary relevance often wins on per-label metrics and loses on exact match.
- Check the residual correlation. If it is near zero for all pairs, binary relevance already captures the structure. Extra complexity will not pay off.
- Check the combination count. If the number of distinct label sets is small relative to the number of samples, label powerset is practical. If it is close to the number of samples, avoid it.
- Consider the cost of invalid outputs. If some combinations are impossible in your domain (for example, "healthy" and "fracture" on the same scan), label powerset or a rule-based filter enforces this. Binary relevance does not.
Common errors
- Reading co-occurrence as causation or as a need for chains. Co-occurrence can come entirely from shared features. Check the residuals first.
- Leaking test labels into the dependence analysis. Compute co-occurrence statistics on the training set only. If you use them to choose a chain order, the order is part of the model.
- Comparing methods on one random split. Rare label combinations can land entirely in one side of the split. Use iterative stratification, covered later in this tutorial, to keep them balanced.
- Forgetting that thresholds interact with chains. A chain passes thresholded predictions to later models. Changing a threshold for an early label changes the inputs for later labels, so tune with the whole chain in the loop.
- Using a chain with a model that outputs only hard labels without checking what is passed on.
ClassifierChainpasses class predictions by default, so later models cannot see the earlier model's uncertainty.
Exercises
Exercise
Two labels have P(B | A) = 0.9, but B is present on 88% of all samples. Is there strong dependence between A and B? Which statistic shows this?
Show answer
No. Lift is about P(A, B) / (P(A) * P(B)) = P(B | A) / P(B) = 0.9 / 0.88, which is about 1.02. This is close to 1, so the labels are nearly independent. The high conditional probability only reflects that B is common.
Exercise
Binary relevance gives a subset accuracy of 0.42 and residual correlations all below 0.05 in absolute value. A teammate proposes switching to a classifier chain. What would you advise, and what would you check first?
Show answer
A chain is unlikely to help much, because residual correlations near zero mean the features already explain the label pattern. Check whether the metric that matters is subset accuracy or a per-label metric, run the comparison over several splits or cross-validation folds, and check whether the low subset accuracy comes from weak per-label models rather than missing dependence.
Exercise
A dataset has 50,000 samples, 80 labels and 30,000 distinct label combinations in the training set. Why is label powerset a poor choice?
Show answer
The label powerset would be a classifier with 30,000 classes, most with only one or two examples. It cannot learn those classes reliably, and it cannot predict any combination absent from the training data. Binary relevance or a chain, with 80 models, is the practical choice.