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())
Download image
Example output
[[1, 1], [0, 2]]