Sub topic 9
Evaluating multiclass models with a confusion matrix
This chapter assumes you know binary precision, recall and F1, and can train a scikit-learn classifier on a train/test split. It shows how those ideas extend to K classes.
Why accuracy is not enough
Accuracy is the share of test rows predicted correctly. It hides which classes get confused. With imbalanced classes, a model can reach high accuracy by ignoring a rare class. A confusion matrix shows where the errors fall.
Reading the matrix
For K classes, the confusion matrix is a K x K table of counts. Scikit-learn puts true classes in rows and predicted classes in columns. Cell (i, j) counts samples whose true class is i and whose predicted class is j. Correct predictions sit on the diagonal.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, classification_report
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
)
clf = LogisticRegression(max_iter=1000).fit(X_train, y_train)
y_pred = clf.predict(X_test)
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))The stratify=y argument keeps class proportions the same in both splits, so each class appears in the test set.
Per-class precision and recall
Each class gets its own precision and recall, computed as if that class were "positive" and all others "negative".
- Recall for class i is the diagonal cell divided by its row sum. It answers: of the samples that truly are class i, how many did we find?
- Precision for class i is the diagonal cell divided by its column sum. It answers: of the samples we called class i, how many were right?
classification_report prints precision, recall, F1 and support (the number of true samples) for every class. It also prints macro and weighted averages, which the next chapter explains.
Common errors
- Swapping axes. Other libraries may put predictions in rows. Check the convention before reading recall off a row.
- Reading counts across classes of different size. A cell of 5 means more in a class of 10 than in a class of 500. Pass
normalize="true"toconfusion_matrixto get each row as a fraction, which makes recall visible directly. - Forgetting the labels order. Rows and columns follow sorted class labels unless you pass
labels=. Set it explicitly when you plot or compare models.
What to do with the result
If one class has low recall, check whether it is rare, and consider class weights or more data. If two classes swap into each other, look for features that separate them. Use accuracy only as a summary, and use the matrix to find where the model fails.
Exercise
In a confusion matrix with true classes in rows, class B has row sum 40, column sum 50, and diagonal value 30. What are the recall and precision for class B?
Show answer
Recall is 30 / 40 = 0.75, because recall divides the diagonal by the row sum. Precision is 30 / 50 = 0.60, because precision divides the diagonal by the column sum.