Sub topic 1
Starting point: what binary classification gives you
Multiclass and multilabel models are built from the same parts as a binary classifier. Before changing any of those parts, it helps to name each one precisely. This chapter lists what a binary classifier produces, which pieces carry over unchanged, and which pieces stop working when the target has more than two outcomes.
Prerequisites
This chapter assumes you already know:
- Binary classification and logistic regression at a basic level.
- How to split data into train and test sets, and the idea of cross-validation.
- Precision, recall and F1 for a binary problem.
- Basic Python and NumPy.
The examples use scikit-learn. You do not need to have used its multiclass tools yet.
The five parts of a binary classifier
A binary classifier has five parts. Every later chapter changes at least one of them.
- Target. A vector
yof shape(n_samples,)with values 0 and 1. Class 1 is the positive class. - Score. The model turns each row of features into one real number. In logistic regression this number is the logit, also called the raw score or decision function. It can be any real value.
- Probability. The sigmoid function,
1 / (1 + exp(-z)), maps the score into the range 0 to 1. The result is read as an estimate of P(y = 1 | x). - Decision rule. A threshold, usually 0.5, turns the probability into a label. A threshold of 0.5 on the probability equals a threshold of 0 on the logit.
- Metrics. Counts of true and false positives and negatives give precision, recall and F1, all computed for the positive class.
Running the pipeline
The code below trains a binary logistic regression on a built-in dataset. It checks that the probability is the sigmoid of the logit. Then it applies two different thresholds to the same probabilities.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=0
)
clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
clf.fit(X_train, y_train)
logit = clf.decision_function(X_test) # shape (n,), any real number
proba = clf.predict_proba(X_test)[:, 1] # shape (n,), P(y = 1)
print("proba equals sigmoid(logit):", np.allclose(proba, 1 / (1 + np.exp(-logit))))
print("y shape:", y_test.shape, "| logit shape:", logit.shape)
for threshold in (0.5, 0.9):
y_pred = (proba >= threshold).astype(int)
print("threshold", threshold)
print(confusion_matrix(y_test, y_pred))
print(" precision:", round(precision_score(y_test, y_pred), 3))
print(" recall: ", round(recall_score(y_test, y_pred), 3))
print(" F1: ", round(f1_score(y_test, y_pred), 3))Three things to notice in this run:
- The first print shows
True. The probability is a fixed function of the score, so the sigmoid adds no information. It only rescales. - The score, the probability and the target all have one value per sample. This one-column shape is what makes binary classification simple.
- Raising the threshold from 0.5 to 0.9 changes the predictions without retraining. Precision usually rises and recall falls, because the model now labels fewer samples as positive. The model and the decision rule are separate objects, and this separation matters for multilabel work later.
The loss behind the model
Logistic regression is fitted by minimizing binary cross-entropy, also called log loss. For one sample with true label y and predicted probability p:
loss = -( y * log(p) + (1 - y) * log(1 - p) )
Only one of the two terms is active for each sample. If y = 1, the loss is -log(p). If y = 0, it is -log(1 - p). A confident wrong answer, such as p = 0.99 when y = 0, produces a large loss. The loss rewards well-calibrated probabilities, not only correct labels at a threshold.
This loss is the one you will see again in the multilabel setting. There it is applied once per label. The multiclass setting uses a related loss in which the scores compete with each other.
What carries over and what breaks
The table lists each part of the binary pipeline and what happens to it when the target has K outcomes.
| Part | Binary | Multiclass (one of K) | Multilabel (any subset of K) |
|---|---|---|---|
| Target shape | `(n,)` of 0 or 1 | `(n,)` of integers 0 to K-1, or `(n, K)` one-hot | `(n, K)` of 0 or 1, several ones allowed |
| Score | 1 per sample | K per sample | K per sample |
| Probability | Sigmoid on 1 score | Softmax over K scores | Sigmoid on each of K scores |
| Decision rule | One threshold | Largest score (argmax) | A threshold per label |
| Metrics | One positive class | Per class, then averaged | Per label, per sample, or averaged |
The last row is where code written for binary problems fails most often. Precision, recall and F1 are defined relative to a positive class. With K classes, you must say which class is positive, or you must compute the metric for every class and average. Scikit-learn does not guess for you.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=0
)
y_pred = LogisticRegression(max_iter=1000).fit(X_train, y_train).predict(X_test)
try:
f1_score(y_test, y_pred) # default average="binary"
except ValueError as error:
print("Binary default fails:", error)
print("macro F1:", round(f1_score(y_test, y_pred, average="macro"), 3))The default average="binary" raises a ValueError because the target has three classes. Passing average="macro" is one valid fix. The choice among macro, micro and weighted averages has real consequences, and a later chapter covers it.
Common errors to avoid
- Treating accuracy as sufficient. On an imbalanced binary problem, a model that always predicts the majority class can score high accuracy. Check precision and recall for the positive class. The same trap grows worse with many classes or labels, where most outcomes are rare.
- Confusing a threshold with the model. Moving the threshold changes the precision and recall trade-off. It does not make the model better at ranking. Threshold-free metrics such as ROC AUC measure ranking quality.
- Assuming the probability is calibrated. A predicted 0.9 does not guarantee that 90% of such cases are positive. Logistic regression is often reasonably calibrated, but many other models are not. This matters when you choose thresholds.
- Reading a multi-column target as binary. A
yof shape(n, 3)is not a binary problem. Passing it to a model that expects(n,)either raises an error or silently flattens the data, depending on the estimator. Always printy.shapeandnp.unique(y)before choosing a model.
What to take into the next chapters
Keep three ideas from the binary case:
- A model produces scores. A separate decision rule turns scores into labels.
- The loss and the probability function belong together. Sigmoid pairs with binary cross-entropy.
- Metrics are always computed relative to a chosen positive outcome.
The remaining chapters keep these ideas and change the shape of the target. They show where a single positive class gives way to K classes that compete or K labels that do not.
Exercise
A binary classifier gives a logit of 0 for a sample. What is the predicted probability, and which label does a threshold of 0.5 assign? If you raise the threshold to 0.9 without retraining, what happens to this sample's label and to the model's recall on average?
Show answer
The sigmoid of 0 is 1 / (1 + exp(0)) = 0.5. With a threshold of 0.5 and the rule "probability >= threshold", the sample is labeled 1. At a threshold of 0.9 the probability 0.5 falls below the cutoff, so the sample is labeled 0. Raising the threshold makes fewer samples positive, so recall on average stays the same or falls, and precision usually rises. The model's scores are unchanged because only the decision rule moved.
Exercise
You call f1_score(y_true, y_pred) on a target with four classes and get a ValueError. Why does it fail, and name one change that fixes it?
Show answer
The default average="binary" expects exactly two classes and a defined positive class, so it cannot summarize four classes in one number. Passing average="macro" (or "micro" or "weighted") computes F1 per class and combines them. Passing average=None returns one F1 per class instead.