Sub topic 2
Binary, Multiclass, Multilabel and Multioutput: Reading the Target Shape
This chapter assumes you can fit a binary logistic regression, split data into train and test sets, and read precision, recall and F1 for a two-class problem. It also assumes basic Python and NumPy. The goal is to look at a target array y and say which kind of problem you have before you pick a model, a loss or a metric.
Why the target shape comes first
A binary classifier answers one yes/no question. Real data often asks for more. An email can be one of "primary", "social" or "promotions". A news article can carry several tags at once. A product listing needs both a category and a condition.
These cases look similar in a spreadsheet but need different outputs, losses, decision rules and metrics. If you misread the shape, the pipeline usually still runs. It just gives results that mean something other than what you think. So the first step is always to read the target.
The four problem types
Two questions identify the type:
- How many target columns does each example have?
- Within a column, are the values mutually exclusive?
| Type | Target columns | Values per example | Example |
|---|---|---|---|
| Binary | 1 | One of 2 classes | Spam or not spam |
| Multiclass | 1 | Exactly one of K classes (K > 2) | Iris species |
| Multilabel | K (binary indicators) | Any subset of K labels, including none | Tags on an article |
| Multioutput | 2 or more | One value per column, columns may differ | Category and condition of a listing |
Multilabel is a special case of multioutput where every column is binary and the columns are the presence or absence of labels from one shared set. Multioutput also covers columns with several classes each (scikit-learn calls this multiclass-multioutput) and columns that are numbers (multioutput regression).
Asking scikit-learn what it sees
scikit-learn inspects a target with type_of_target. Its answer is what estimators and metrics use to decide how to behave, so it is worth checking yourself.
import numpy as np
from sklearn.utils.multiclass import type_of_target
targets = {
"spam flag": [0, 1, 1, 0],
"iris species": ["setosa", "versicolor", "virginica", "setosa"],
"tags (indicator)": np.array([[1, 0, 1], [0, 1, 0], [0, 0, 0]]),
"color and size": np.array([[0, 2], [1, 3], [2, 0]]),
"price": [9.5, 12.0, 7.25],
}
for name, y in targets.items():
print(f"{name:18} -> {type_of_target(y)}")The output is:
spam flag -> binary
iris species -> multiclass
tags (indicator) -> multilabel-indicator
color and size -> multiclass-multioutput
price -> continuousThe names map onto the table. multilabel-indicator is multilabel, and multiclass-multioutput is multioutput with multi-valued columns. The last row shows that a numeric target with non-integer values is read as regression, not classification.
What makes multilabel different
The defining property of multilabel data is that the labels are not mutually exclusive. Row sums of the indicator matrix show this directly.
import numpy as np
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.utils.multiclass import type_of_target
tags = [["python", "ml"], ["ml"], [], ["python", "web", "ml"]]
mlb = MultiLabelBinarizer()
Y = mlb.fit_transform(tags)
print(mlb.classes_)
print(Y)
print("row sums:", Y.sum(axis=1))
print(type_of_target(Y))MultiLabelBinarizer turns lists of tags into a matrix with one column per label. The row sums are [2 1 0 3]. In a multiclass problem every row sum would be exactly 1, because each example has one class. In multilabel data a row may have zero labels, one label or many.
The empty row is legal. An article with no tags is a valid example, and a good multilabel model must be able to predict "none of the above". A multiclass model cannot do this unless you add an explicit "other" class.
Multioutput: several questions at once
Multioutput targets ask independent questions about the same input. The columns do not share a label vocabulary, and they may have different numbers of classes. Here is a small example that pairs the iris species (three classes) with a made-up binary column.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.multioutput import MultiOutputClassifier
from sklearn.utils.multiclass import type_of_target
X, species = load_iris(return_X_y=True)
wide_sepal = (X[:, 1] > 3.0).astype(int) # a second, unrelated question
Y = np.column_stack([species, wide_sepal])
print(Y.shape, type_of_target(Y))
model = MultiOutputClassifier(LogisticRegression(max_iter=1000)).fit(X, Y)
print(model.predict(X[:3]).shape)The target has shape (150, 2) and is reported as multiclass-multioutput. MultiOutputClassifier fits one classifier per column, and predict returns one value per column for each row, so the output shape is (3, 2).
Same array, different meaning
Shape does not settle everything. Two situations need a decision from you.
- A two-column 0/1 matrix.
type_of_targetcalls itmultilabel-indicator. It may actually be two unrelated binary questions, such as "churned" and "opened support ticket". Mathematically they are the same array. The difference is the meaning of the columns. If they are labels drawn from one set (tags), treat the problem as multilabel. If they are separate questions, treat it as multioutput. Many tools handle both the same way, so the distinction matters most for how you evaluate and report results. - A one-hot matrix. If every row sums to exactly 1, the matrix is a multiclass target in disguise. Convert it to class indices with
argmax(axis=1)and use a multiclass pipeline. Treating it as multilabel throws away the guarantee that one class is active.
Common reading errors
- Integer-coded numbers. Ages or counts stored as integers are read as multiclass if they have many distinct values. A model would then treat 41 and 42 as unrelated categories. Check that a classification target is really categorical.
- A rare class missing from a split. If a class never appears in the training split, the training target may look binary even though the full data is multiclass. Use stratified splits so every class appears on both sides.
- Ordered classes. Ratings of 1 to 5 are multiclass by shape, but the order carries information that plain multiclass models ignore. Decide deliberately whether you want ordinal modeling or regression instead.
- Mixed types in one column. Strings and numbers in the same column, or
NaNvalues in a label column, can maketype_of_targetreturnunknownor raise an error. Clean labels first. - Hidden multilabel data. A column holding values like
"a,b"or"a|b"is a multilabel target stored as text. Split it and binarize it. Do not treat each combination as its own class unless you mean to.
What the shape decides
The target shape fixes the rest of the pipeline. The later chapters cover each item below in detail.
| Choice | Binary | Multiclass | Multilabel |
|---|---|---|---|
| Output activation | One sigmoid | Softmax over K scores | K independent sigmoids |
| Loss | Binary cross-entropy | Categorical cross-entropy | Binary cross-entropy per label |
| Decision rule | Threshold | Argmax | Threshold per label |
| Typical metrics | Accuracy, F1 | Confusion matrix, averaged F1 | Hamming loss, subset accuracy, F1 |
Always identify the shape first. Everything in this table follows from that identification.
Exercise
A hospital model predicts, for each patient, which of 12 conditions are present. Some patients have none and some have several. What is the problem type, what shape and row sums does the target have, and why is plain multiclass the wrong choice?
Show answer
It is multilabel. The target is an indicator matrix with n rows and 12 binary columns. Row sums range from 0 up to 12, and a row sum of 0 means no condition is present. Multiclass is wrong because it forces exactly one class per patient, so it cannot represent patients with zero or several conditions.
Exercise
You receive a target matrix with 3 columns of 0/1 values, and every row sums to exactly 1. What does typeoftarget report, and what should you do?
Show answer
It reports multilabel-indicator, because the array is a 2D matrix of 0/1 values. Since every row sums to 1, the data is really a one-hot multiclass target. Convert it with y.argmax(axis=1) to class indices and use a multiclass pipeline, so the model can use the one-class-per-row constraint.
Exercise
A listing dataset has a "category" column with 20 values and a "condition" column with values new, used or refurbished. Which problem type is this, and which scikit-learn wrapper fits one classifier per column?
Show answer
It is multioutput (multiclass-multioutput in scikit-learn terms), because the two columns are different questions with different class sets. MultiOutputClassifier fits one classifier per column.