Sub topic 3
Encoding targets: indices, one-hot and multi-hot matrices
This chapter assumes you can train a binary classifier in scikit-learn, split data into train and test sets, and read a NumPy array's shape. It covers how a label column becomes the array a model trains on. The next chapters cover the losses and output layers that consume these arrays.
Why encoding comes first
A model never sees the words "cat" or "python". It sees numbers, and the layout of those numbers must match the problem. The same set of K labels can be stored in three layouts:
- Class indices: one integer per example, from 0 to K-1.
- One-hot matrix: K columns per example, with exactly one 1.
- Multi-hot matrix: K columns per example, with any number of 1s, including none.
The first two describe multiclass targets. The third describes multilabel targets. Choosing the wrong layout does not always raise an error. A loss function can accept the array and still train on a meaning you did not intend.
The three layouts side by side
| Layout | Shape for N examples, K labels | Values per row | Used for |
|---|---|---|---|
| Class indices | `(N,)` | One integer in 0..K-1 | Multiclass |
| One-hot | `(N, K)` | Exactly one 1 | Multiclass |
| Multi-hot | `(N, K)` | Zero or more 1s | Multilabel |
Binary targets are the K=2 special case. They are usually stored as a single 0/1 column of shape (N,), where 1 marks the positive class.
Class indices
Class indices map each label to an integer. The mapping must be stored, because you need it to turn predictions back into names. LabelEncoder does this and sorts the labels alphabetically.
import numpy as np
from sklearn.preprocessing import LabelEncoder
y_text = np.array(["cat", "dog", "bird", "dog", "cat"])
le = LabelEncoder()
y_idx = le.fit_transform(y_text)
print(le.classes_) # ['bird' 'cat' 'dog']
print(y_idx) # [1 2 0 2 1]
print(le.inverse_transform([0, 2])) # ['bird' 'dog']The index 2 is not "bigger" than the index 1 in any useful sense. Indices are names, not quantities. Do not feed them to a regression model, and do not read a difference between two indices as a distance between two classes.
One-hot encoding
A one-hot row has a 1 in the column of the true class and 0 elsewhere. You can build it from indices with an identity matrix.
import numpy as np
from sklearn.preprocessing import LabelBinarizer
y_text = np.array(["cat", "dog", "bird", "dog", "cat"])
y_idx = np.array([1, 2, 0, 2, 1])
K = 3
onehot = np.eye(K, dtype=int)[y_idx] # row i of eye(K) is the one-hot for class i
print(onehot)
lb = LabelBinarizer()
print(lb.fit_transform(y_text)) # same matrix, columns ordered bird, cat, dog
print(lb.classes_)
two = LabelBinarizer().fit_transform(["no", "yes", "yes"])
print(two.shape) # (3, 1): two classes collapse to one columnThe last line shows an edge case. With exactly two classes, LabelBinarizer returns a single column, matching the binary convention. If your code expects (N, K) for every K, handle K=2 separately.
A sanity check for any one-hot matrix is that each row sums to 1:
assert (onehot.sum(axis=1) == 1).all()Multi-hot encoding
In a multilabel problem, each example has a set of labels. The set can have one label, many labels, or none. MultiLabelBinarizer turns a list of label lists into a multi-hot matrix.
from sklearn.preprocessing import MultiLabelBinarizer
tags = [
["python", "ml"],
["ml"],
[],
["web", "python", "ml"],
]
mlb = MultiLabelBinarizer()
Y = mlb.fit_transform(tags)
print(mlb.classes_) # ['ml' 'python' 'web']
print(Y)
# [[1 1 0]
# [1 0 0]
# [0 0 0]
# [1 1 1]]
print("labels per example:", Y.sum(axis=1)) # [2 1 0 3]
print("examples per label:", Y.sum(axis=0)) # [3 2 1]
print("label cardinality:", Y.sum(axis=1).mean()) # 1.5Three details matter here:
- Row sums vary. A multi-hot row can sum to 0, 1, or more. Only one-hot rows are required to sum to 1.
- An all-zero row is valid. The third example has no tags. In multiclass there is no equivalent, because every example must belong to a class. If you want "none of the above" in a multiclass problem, add it as an explicit class.
- Column sums show label frequency. They are the first thing to inspect when you suspect imbalance, which a later chapter covers.
Keeping the column order stable
A matrix column has no name. Its meaning comes entirely from the position stored in classes_. If you fit one encoder on the training set and another on the test set, the columns can silently disagree whenever the two sets contain different labels.
Fit the encoder once, on the training labels or on a fixed vocabulary, and reuse it.
from sklearn.preprocessing import MultiLabelBinarizer
vocab = ["ml", "python", "web", "devops"]
mlb = MultiLabelBinarizer(classes=vocab)
Y_train = mlb.fit_transform([["python", "ml"], ["web"]])
Y_test = mlb.transform([["devops", "ml"]])
print(Y_train.shape, Y_test.shape) # (2, 4) (1, 4)
print(Y_test) # [[1 0 0 1]]Passing classes= fixes the order and includes labels that do not appear in the training data, such as "devops". Without it, a label missing from the training sample would have no column at all.
Unseen labels behave differently across the encoders:
LabelEncoder.transformraises aValueErrorfor a label it has not seen.MultiLabelBinarizer.transformemits a warning and ignores the unknown label. Your matrix then quietly loses information, so treat that warning as an error in a pipeline.
Multioutput targets
A multioutput target has M separate targets for each example, such as a colour and a size. It is stored as a matrix of shape (N, M). Unlike a multi-hot matrix, each column holds its own class indices and can have more than two values.
import numpy as np
# Column 0: colour (0=red, 1=green, 2=blue). Column 1: size (0=small, 1=large).
Y_multi = np.array([
[0, 1],
[2, 0],
[1, 1],
])
print(Y_multi.shape) # (3, 2)The shapes of Y_multi and a multi-hot matrix can look alike, but the meaning differs. In a multi-hot matrix every column answers "does this label apply?" In a multioutput matrix every column answers a different question, with its own set of answers. Check np.unique on each column if you are unsure which one you have.
Matching the encoding to the loss
Frameworks pick the layout you must supply. The table lists common pairings.
| Library and loss | Expected target |
|---|---|
| scikit-learn classifiers, multiclass | Class labels or indices, shape `(N,)`, strings allowed |
| scikit-learn classifiers, multilabel | Multi-hot matrix, shape `(N, K)` |
| Keras `SparseCategoricalCrossentropy` | Class indices, shape `(N,)` |
| Keras `CategoricalCrossentropy` | One-hot matrix, shape `(N, K)` |
| PyTorch `CrossEntropyLoss` | Class indices as `torch.long`, shape `(N,)` |
| PyTorch `BCEWithLogitsLoss` | Multi-hot matrix as float, shape `(N, K)` |
Scikit-learn encodes multiclass labels internally, so you usually pass the raw strings or integers. You still need an explicit encoding when you build the arrays yourself for a neural network, or when you need the class order for reading probability columns.
Common mistakes
- Passing a one-hot matrix to a scikit-learn multiclass classifier. A 2D array with several columns is read as a multilabel or multioutput target, so you get a different model than you intended.
- Using multi-hot targets with softmax. Softmax forces the scores to sum to 1, so it cannot represent two true labels at once.
- Fitting separate encoders on train and test data, which can misalign the columns.
- Forgetting that K=2 collapses to a single column in
LabelBinarizer. - Reading the label order from memory instead of from
classes_.
Exercise
A dataset has 1,000 news articles. Each article has between 0 and 4 topic tags drawn from 6 possible topics. You build the target with MultiLabelBinarizer. What shape does it have, what can each row sum to, and why can't you encode this target as a single column of class indices?
Show answer
The matrix has shape (1000, 6). Each row can sum to anything from 0 to 4, since an article may have no tags or up to four. A single column of class indices stores one integer per article, so it can hold only one label. It cannot represent an article with several tags, and it has no way to represent an article with none.
Exercise
You fit LabelEncoder on the training labels ["a", "b", "c"] and then call transform on test labels that include "d". What happens, and what would MultiLabelBinarizer do with an unseen tag in the same situation?
Show answer
LabelEncoder.transform raises a ValueError because "d" was not seen during fitting. MultiLabelBinarizer.transform emits a warning and ignores the unknown tag, so the row loses that label without stopping the program. To avoid both outcomes, fix the vocabulary up front, for example with MultiLabelBinarizer(classes=...).