Sub topic 6
Classification: predicting a category
Classification is the supervised learning task where the label is one of a fixed set of categories. This chapter assumes you know basic Python, can read NumPy arrays, and have met the idea of a train/test split from the earlier chapters on supervised learning. It covers the task, how a classifier produces its answer, how to evaluate it, and the errors that most often mislead people.
What makes a task a classification task
A task is classification when the label is a class, meaning a value from a finite list with no meaningful arithmetic between values. Examples:
- An email is
spamornot spam. - A photo shows a
cat, adog, or abird. - An iris flower belongs to
setosa,versicolor, orvirginica. - A transaction is
fraudorlegitimate.
The classes may be stored as integers such as 0, 1, and 2, but those numbers are only names. Class 2 is not "twice" class 1. If you need to predict a quantity such as a price or a temperature, the task is regression, which the next chapter covers.
Classification tasks are named by how many classes they have:
| Type | Classes per example | Example |
|---|---|---|
| Binary | Exactly two | Spam or not spam |
| Multiclass | Three or more, exactly one is correct | Iris species |
| Multilabel | Several can be correct at once | Tags on a news article |
Most of this chapter is about binary and multiclass problems. Multilabel problems are usually handled by training one binary classifier per label.
From features to a predicted class
A classifier is a function learned from data. It takes the feature vector of one example and returns a class. Most classifiers do this in two steps:
- Compute a score for each class from the features and the learned parameters.
- Pick the class with the highest score, or the class whose probability passes a threshold.
Logistic regression, despite its name, is a classification model. For a binary problem it computes a weighted sum of the features and passes it through the sigmoid function, which squashes any number into the range 0 to 1. The result is read as the estimated probability of the positive class. For several classes, scikit-learn's implementation uses the softmax function, which turns one score per class into probabilities that sum to 1.
The decision rule is a separate choice from the model. The default rule is "take the most probable class". Later sections show why you sometimes change it.
A complete example
This program trains a classifier on the iris data, then reports more than a single accuracy number.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
data = load_iris()
X, y = data.data, data.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
probabilities = model.predict_proba(X_test)
print("accuracy:", accuracy_score(y_test, predictions))
print("first example probabilities:", probabilities[0].round(3))
print("classes:", model.classes_)
print(confusion_matrix(y_test, predictions))
print(classification_report(y_test, predictions, target_names=data.target_names))Points to notice:
stratify=ykeeps the class proportions the same in the training and test sets. Without it, a small class can end up almost absent from one side by chance.predictreturns class labels.predict_probareturns one probability per class, with columns in the order ofmodel.classes_.max_iter=200gives the optimizer enough steps to converge on this data. If scikit-learn emits aConvergenceWarning, the optimizer stopped early. Scaling the features or raisingmax_iterusually fixes it.
Reading a confusion matrix
Accuracy is the fraction of predictions that are correct. It hides which mistakes the model makes. A confusion matrix is a table with one row per true class and one column per predicted class. Cell (i, j) counts the examples whose true class is i and whose predicted class is j. Correct predictions sit on the diagonal, and every off-diagonal count is a specific kind of mistake.
For a binary problem, the four cells have standard names, with one class designated "positive":
| Row | Predicted positive | Predicted negative |
|---|---|---|
| Actually positive | True positive (TP) | False negative (FN) |
| Actually negative | False positive (FP) | True negative (TN) |
From these counts come the metrics you will use most:
- Accuracy = (TP + TN) / all examples.
- Precision = TP / (TP + FP). Of the examples the model flagged positive, how many really were?
- Recall = TP / (TP + FN). Of the real positives, how many did the model find?
- F1 score is the harmonic mean of precision and recall. It is low if either one is low.
In scikit-learn, confusion_matrix puts true classes in rows and predicted classes in columns, matching the description above. Other libraries sometimes transpose it, so check the documentation when you compare outputs.
When accuracy misleads
Suppose only 5% of transactions are fraud. A model that always answers "legitimate" is 95% accurate and catches no fraud. This is the class imbalance problem, and the next example shows it with a baseline that does nothing but predict the most common class.
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, precision_score, recall_score
X, y = make_classification(
n_samples=2000,
n_features=10,
n_informative=5,
weights=[0.95, 0.05],
random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
for name, clf in [("baseline", baseline), ("logistic", model)]:
pred = clf.predict(X_test)
print(
name,
"accuracy", round(accuracy_score(y_test, pred), 3),
"precision", round(precision_score(y_test, pred, zero_division=0), 3),
"recall", round(recall_score(y_test, pred), 3),
)
# Lower the threshold to trade precision for recall.
proba = model.predict_proba(X_test)[:, 1]
for threshold in (0.5, 0.2):
pred = (proba >= threshold).astype(int)
print(
"threshold", threshold,
"precision", round(precision_score(y_test, pred, zero_division=0), 3),
"recall", round(recall_score(y_test, pred), 3),
)The baseline has high accuracy and a recall of 0, because it never predicts the positive class. Always compute such a baseline first. If your model barely beats it, the model has learned little.
The second loop shows the decision threshold. Lowering it from 0.5 to 0.2 labels more examples positive. Recall usually rises and precision usually falls. Which side to favor depends on the cost of each mistake:
- Screening for a serious disease: a missed case (false negative) is costly, so favor recall.
- Automatically blocking a customer's account: a wrongful block (false positive) is costly, so favor precision.
Common classifiers and when they fit
Many model families can classify. Each exposes the same fit, predict, and predict_proba interface in scikit-learn, so you can swap them with little code change.
- Logistic regression is fast, works well as a first model, and gives probabilities that are often reasonably calibrated.
- Decision trees split the data with a sequence of yes/no questions on features. They are easy to read but overfit when allowed to grow without limit, as the earlier chapter on generalization showed.
- Nearest neighbors predict the majority class among the k closest training examples. They need features on comparable scales.
- Ensembles of trees, such as random forests and gradient boosting, are strong defaults for tabular data.
Common errors
- Reporting accuracy on imbalanced data. Check class counts with
numpy.bincount(y)and report precision and recall for the class you care about. - Evaluating on training data. A model can score perfectly on examples it has memorized. Only held-out data estimates real performance.
- Leakage through preprocessing. Fitting a scaler on the full dataset before splitting lets test-set statistics influence training. Fit preprocessing on the training set only, or wrap the steps in a
Pipeline. - Treating probabilities as certainties. A predicted probability of 0.9 means the model's confidence. It is not a guarantee that 90% of such cases are positive unless you have checked calibration.
- Ignoring the order of
predict_probacolumns. Always map columns throughmodel.classes_.
Summary
Classification predicts one of a fixed set of categories. The model scores each class, a decision rule picks the answer, and the right metric depends on the cost of each kind of error. A baseline, a stratified split, and a confusion matrix catch most of the mistakes beginners make.
Exercise
A model screens 1,000 patients for a rare condition that 10 of them have. It predicts "healthy" for everyone. Compute its accuracy and its recall for the condition. Then say which direction you would move the decision threshold if missing a sick patient is far worse than a false alarm.
Show answer
Accuracy is 990 / 1000 = 0.99, because all 990 healthy patients are classified correctly. Recall is 0 / 10 = 0, because none of the 10 sick patients are found. Since false negatives are the costly error, lower the threshold (for example from 0.5 to 0.2) so more patients are flagged positive. This raises recall at the cost of lower precision.
Exercise
In the iris example, model.predict_proba(X_test)[0] returns three numbers. What do they sum to, and how do you find which class each number belongs to?
Show answer
They sum to 1, since they are the probabilities of the three classes for that one example. The columns follow the order of model.classes_, so model.classes_[i] is the class whose probability is in column i. predict returns the class with the largest of the three.