Reading history

Multi-Label Classification in Python

6 min read 0 views

Learn multi-label classification in Python with MultiOutputClassifier and ClassifierChain, and measure it with Hamming loss, exact match and F1.

A news article about a cricket board’s budget is about sports and economy. A film can be both comedy and romance. When one item can carry several labels at once, you have a multi-label problem. In this lesson you will build multi-label models in scikit-learn and learn the metrics that make sense for them.

In this lesson you will learn

  • How multi-label differs from multiclass classification
  • How to store several labels per row as a 0/1 matrix
  • Binary relevance with MultiOutputClassifier
  • Classifier chains, which let labels help each other
  • Hamming loss, exact-match accuracy and micro and macro F1

You should know multiclass classification and precision, recall and F1.

Multiclass vs Multi-Label

MulticlassMulti-label
Labels per itemExactly oneZero, one or many
ExampleWhich digit is this, 0 to 9?Which tags fit this article?
Target shapeOne columnOne 0/1 column per label

In multi-label data, the target Y is a matrix. Each row is an item and each column is one label. A 1 means “this label applies”. A row like [0 1 0 1] means the article is tagged sports and tech.

Two Ways to Build the Model

The simplest plan is binary relevance: train one yes/no classifier per label and run them all. It is easy, but each classifier ignores the other labels. A classifier chain fixes that. The first classifier predicts label 1. The second sees the inputs plus label 1, the third also sees label 2, and so on along the chain. This helps when labels go together, like “cyclone” and “flood”.

import numpy as np
from sklearn.datasets import make_multilabel_classification
from sklearn.model_selection import train_test_split
from sklearn.multioutput import MultiOutputClassifier, ClassifierChain
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import hamming_loss, accuracy_score, f1_score

# Each news article can have SEVERAL tags at once: politics, sports, economy, tech
tags = ["politics", "sports", "economy", "tech"]
X, Y = make_multilabel_classification(n_samples=1000, n_features=20, n_classes=4,
                                      n_labels=2, random_state=1)
print("label matrix shape:", Y.shape)
print("first 3 rows of Y:\n", Y[:3])

X_tr, X_te, Y_tr, Y_te = train_test_split(X, Y, test_size=0.3, random_state=0)

# Binary relevance: one independent yes/no classifier per tag
br = MultiOutputClassifier(LogisticRegression(max_iter=1000)).fit(X_tr, Y_tr)
# Classifier chain: each classifier also sees the previous tags' predictions
cc = ClassifierChain(LogisticRegression(max_iter=1000), order=[0, 1, 2, 3],
                     random_state=0).fit(X_tr, Y_tr)

for name, model in [("one model per tag", br), ("classifier chain", cc)]:
    P = model.predict(X_te).astype(int)
    print(f"\n{name}:")
    print(f"  Hamming loss       {hamming_loss(Y_te, P):.3f}  (share of wrong tag decisions)")
    print(f"  exact-match acc.   {accuracy_score(Y_te, P):.3f}  (all 4 tags right)")
    print(f"  micro F1           {f1_score(Y_te, P, average='micro'):.3f}")

print("\npredicted tags for one article:",
      [t for t, on in zip(tags, br.predict(X_te[:1])[0]) if on])

Output

label matrix shape: (1000, 4)
first 3 rows of Y:
 [[0 1 0 1]
 [0 0 0 0]
 [1 1 0 1]]

one model per tag:
  Hamming loss       0.179  (share of wrong tag decisions)
  exact-match acc.   0.463  (all 4 tags right)
  micro F1           0.812

classifier chain:
  Hamming loss       0.163  (share of wrong tag decisions)
  exact-match acc.   0.547  (all 4 tags right)
  micro F1           0.828

predicted tags for one article: ['politics']
  • make_multilabel_classification makes fake data with 4 labels. Some rows have several 1s and the second row has none, which is allowed.
  • MultiOutputClassifier wraps any classifier and fits one copy per label column.
  • ClassifierChain does slightly better on every metric here, because the labels in this data are linked.
  • The last line turns one row of 0s and 1s back into tag names.

Measuring Multi-Label Models

Plain accuracy is too strict here. If an article has 4 tags and we get 3 right, it still counts as a miss. So we use several measures together.

MetricQuestion it answersBetter
Hamming lossWhat share of single tag decisions were wrong?Lower
Exact-match accuracyFor how many items were all tags right?Higher
Micro F1F1 over every tag decision pooled togetherHigher
Macro F1Average of the F1 for each label, so rare labels count equallyHigher

A Hamming loss of 0.163 means about 1 in 6 tag decisions was wrong. Exact-match accuracy is only 0.547, since one wrong tag spoils the whole row. Both views are useful.

Models That Handle Many Labels Directly

Some scikit-learn models, such as decision trees, random forests and k-nearest neighbours, accept a 0/1 label matrix with no wrapper. Let us look at the report for each tag.

import numpy as np
from sklearn.datasets import make_multilabel_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report

tags = ["politics", "sports", "economy", "tech"]
X, Y = make_multilabel_classification(n_samples=1000, n_features=20, n_classes=4,
                                      n_labels=2, random_state=1)
X_tr, X_te, Y_tr, Y_te = train_test_split(X, Y, test_size=0.3, random_state=0)

# Some models accept a 2-D label matrix directly. Random forest is one of them.
rf = RandomForestClassifier(n_estimators=200, random_state=0).fit(X_tr, Y_tr)
P = rf.predict(X_te)
print(classification_report(Y_te, P, target_names=tags, zero_division=0))

# How many tags does each article get, truly and predicted?
print("tags per article (true):     ", np.bincount(Y_te.sum(axis=1), minlength=5))
print("tags per article (predicted):", np.bincount(P.sum(axis=1), minlength=5))

Output

              precision    recall  f1-score   support

    politics       0.80      0.91      0.85       180
      sports       0.82      0.98      0.89       209
     economy       0.00      0.00      0.00        27
        tech       0.76      0.89      0.82       151

   micro avg       0.80      0.88      0.84       567
   macro avg       0.60      0.69      0.64       567
weighted avg       0.76      0.88      0.82       567
 samples avg       0.77      0.81      0.76       567

tags per article (true):      [37 78 93 65 27]
tags per article (predicted): [ 14  74  82 130   0]
  • Three tags score well, but economy gets an F1 of 0. It appears in only 27 test rows, and the forest never predicts it.
  • Micro F1 is 0.84, so it hides this failure. Macro F1 is only 0.64, because it gives the rare tag equal weight. Always check per-label results.
  • The model also never predicts 4 tags at once, even though 27 articles have them. It plays safe with common tags.
  • To help a rare tag, try class_weight="balanced" or lower its decision threshold. See imbalanced data.

Common Mistakes

  1. Treating it as multiclass. Making one class per combination, like “sports+tech”, blows up the number of classes and leaves most with few examples.
  2. Reporting only micro F1. It can look good while a rare label is never predicted.
  3. Splitting without care. A random split can leave a rare label with almost no test rows. Check label counts in both parts.
  4. Using one threshold for every label. Rare labels often need a lower threshold than common ones.

Practice Exercises

Exercise 1. An article has true tags [1 0 1 0] and the model predicts [1 1 1 0]. What are the Hamming loss and exact-match accuracy for this one row?

Show answer

One of the four tag decisions is wrong, so the Hamming loss is 1/4 = 0.25. Not all tags match, so exact-match accuracy is 0.

Exercise 2. When would a classifier chain help more than binary relevance?

Show answer

When labels depend on each other. If “flood” usually comes with “rain”, knowing the rain prediction helps the flood classifier. If labels are unrelated, a chain gives little benefit.

Frequently Asked Questions

How do I turn lists of tags into a 0/1 matrix?

Use MultiLabelBinarizer from sklearn.preprocessing. It turns lists such as [“sports”, “tech”] into rows of 0s and 1s, one column per tag, and can turn them back.

Does the order of a classifier chain matter?

Yes, it can change the results. A common trick is to train several chains with random orders and average them, or put the easiest labels first.

Summary

  • Multi-label means each item can have any number of labels.
  • The target is a 0/1 matrix with one column per label.
  • Binary relevance trains one model per label; chains let labels inform each other.
  • Use Hamming loss, exact match and both micro and macro F1, and check each label.

Next: Semi-Supervised Learning in Python.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *