Classification and confusion matrices

scikit-learn 1.9.1

Predict categorical labels and see which classes a classifier misses.

On this page

Train a decision tree

A decision tree learns feature splits that separate categories. Deep trees can memorize training details. Use a held-out set or cross-validation and choose tree settings on training data.

from sklearn.tree import DecisionTreeClassifier

X = [[40], [55], [95], [130]]
y = ["small", "small", "large", "large"]
model = DecisionTreeClassifier(max_depth=2, random_state=42).fit(X, y)
print(model.predict([[45], [120]]).tolist())
Example output
['small', 'large']

Read errors by class

In scikit-learn’s confusion matrix, rows are true labels and columns are predicted labels. Precision asks how often positive predictions were correct. Recall asks how many true positives the model found. Inspect per-class scores when a class is rare.

from sklearn.metrics import confusion_matrix

print(confusion_matrix([0, 0, 1, 1], [0, 1, 1, 1], labels=[0, 1]).tolist())
Actual class 0 has one prediction of each class. Actual class 1 has zero predictions of class 0 and two of class 1. Download image
With class 1 as positive, there is one false positive and zero false negatives.
Example output
[[1, 1], [0, 2]]

Official references