Sub topic 6
Classification: predicting a category
This chapter assumes you can read basic Python and know what features and labels are. It also assumes you know that supervised learning trains on labeled examples. Here you will see what makes a task a classification task, run a classifier, and learn the errors that most often trip people up.
What classification is
Classification is a supervised task where the label is a category, such as "spam" or "not spam", or one of three flower species. The model learns from examples whose correct category is known. Then it assigns a category to new examples.
The set of possible categories is fixed before training. Each category is called a class. The task falls into one of these types:
- Binary classification has two classes, such as fraud or not fraud.
- Multiclass classification has three or more classes, where each example gets exactly one, such as the iris species.
- Multilabel classification lets one example have several labels at once, such as the tags on a photo.
If the label is a number on a continuous scale, such as a price, the task is regression instead. That is the next chapter.
How a classifier decides
Most classifiers do not output a class directly. They compute a score for each class, often a probability, and pick the highest one. Logistic regression, despite its name, is a classification model. It combines the features with learned weights and turns the result into class probabilities.
A worked example
The code below trains a classifier on the iris dataset. Each example has four measurements, and the label is one of three species. It then reports probabilities for one flower.
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
X, y = load_iris(return_X_y=True)
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)
print(accuracy_score(y_test, predictions))
print(model.predict_proba(X_test[:1]))
print(predictions[0], y_test[0])The first print shows the fraction of test flowers classified correctly. predict_proba returns one probability per class for the first test flower, and the values sum to 1. predict returns the class with the highest probability.
The split uses stratify=y. This keeps the class proportions the same in the training and test sets. Without it, a small dataset could end up with too few examples of one class in the test set.
Common errors
- Trusting accuracy on imbalanced data. If 99% of emails are not spam, a model that always answers "not spam" scores 99% accuracy and catches nothing. Look at per-class results, such as precision and recall, which a later chapter covers.
- Scoring on training data. A model can memorize its training examples. Always measure on examples it has not seen.
- Treating class numbers as quantities. Labels like 0, 1, and 2 are names. The model should not assume that class 2 is "twice" class 1.
- Reading probabilities as certainty. A probability of 0.9 means the model is fairly confident. It does not mean the model is right 90% of the time unless it has been checked for calibration.
Exercise
A hospital wants a model that outputs a patient's risk of readmission as a percentage from 0 to 100, and another model that outputs "readmitted" or "not readmitted". Which is classification, and what is the other?
Show answer
The model that outputs "readmitted" or "not readmitted" is binary classification, because its label is a category. The model that outputs a percentage score as a continuous number would be regression. A classifier can still output a probability internally, but its final answer is a class.
Exercise
In the example code, what does stratify=y do, and why does it matter for a small dataset?
Show answer
It keeps the proportion of each class the same in the training and test sets. On a small dataset, a random split could leave a class with very few or no test examples, which would make the test score unreliable.