Sub topic 3
Encoding targets: indices, one-hot and multi-hot matrices
This chapter assumes you know binary classification, basic NumPy and scikit-learn usage. Before you pick a loss or a model, you need the target in the right numeric form. The form depends on the problem type from the previous chapter, and a wrong form usually fails silently.
Three target formats
A class index vector has one integer per sample, from 0 to K-1. It suits multiclass problems, where each sample has exactly one class.
A one-hot matrix has shape (n_samples, K). Each row has a single 1 and K-1 zeros. It is the same information as the index vector, laid out as columns.
A multi-hot matrix (also called a label indicator matrix) has the same shape. Each row can contain any number of 1s, including none. It suits multilabel problems.
| Format | Shape | Row sum | Problem type |
|---|---|---|---|
| Class indices | `(n,)` | not applicable | Multiclass |
| One-hot | `(n, K)` | always 1 | Multiclass |
| Multi-hot | `(n, K)` | 0 to K | Multilabel |
Building each format
The LabelEncoder class maps class names to indices. The MultiLabelBinarizer class builds a multi-hot matrix from a list of label sets.
import numpy as np
from sklearn.preprocessing import LabelEncoder, MultiLabelBinarizer
# Multiclass: one label per sample.
y_class = ["cat", "dog", "bird", "dog"]
le = LabelEncoder()
idx = le.fit_transform(y_class)
one_hot = np.eye(len(le.classes_), dtype=int)[idx]
print(le.classes_, idx)
print(one_hot)
print("one-hot row sums:", one_hot.sum(axis=1))
# Multilabel: a set of labels per sample, possibly empty.
y_multi = [["sports", "news"], ["tech"], [], ["news", "tech"]]
mlb = MultiLabelBinarizer()
Y = mlb.fit_transform(y_multi)
print(mlb.classes_)
print(Y)
print("multi-hot row sums:", Y.sum(axis=1))Both encoders sort class names alphabetically. Column 0 of Y is news, not the first label you happened to see. Keep the fitted encoder, because you need classes_ to turn predictions back into names.
Which format does the model want?
Libraries differ, so check what each one expects.
- scikit-learn multiclass estimators accept class indices or the original strings. Do not pass a one-hot matrix as
y. A 2Dyof 0s and 1s is read as multilabel, and no error warns you. - scikit-learn multilabel estimators, such as
OneVsRestClassifieron a matrix, expect a multi-hot matrix. - In deep learning frameworks, sparse categorical cross-entropy takes class indices. Categorical cross-entropy takes one-hot rows. Binary cross-entropy applied per output takes a multi-hot matrix.
Common errors
- Reading a one-hot matrix as multilabel. A one-hot matrix is a valid multi-hot matrix with exactly one 1 per row. The model trains without complaint but uses per-label decisions, so it may predict zero or several classes for a sample.
- Mismatched column order. If you fit separate encoders on the train and test sets, the columns can differ. Fit once on the training labels and reuse the encoder.
- Ordinal misuse. Class indices carry no order. Never feed them as a numeric target to a regression model, and never use them as an input feature without one-hot encoding.
- Ignoring all-zero rows. In multilabel data, a row of zeros means "no label applies". Decide whether this is valid for your task. Some metrics and chain methods treat it specially.
Exercise
A dataset has 5 classes and 200 samples, and each sample belongs to exactly one class. You build a 200 by 5 matrix of 0s and 1s and pass it to a scikit-learn classifier as y. What goes wrong, and what should you pass instead?
Show answer
scikit-learn treats the matrix as a multilabel target, so the model makes five independent yes/no decisions per sample and can predict zero or several classes. Pass a 1D vector of 200 class indices, for example y = onehot.argmax(axis=1), or the original class names.