Accuracy is the fraction correct. It hides which mistakes you made. A confusion matrix counts true vs predicted labels. classification_report adds precision, recall, and F1 per class.
Goal
Print accuracy, a confusion matrix, and a classification report, then draw the matrix.
Numbers
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
X, y = make_classification(n_samples=200, n_features=4, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
clf = LogisticRegression(max_iter=200)
clf.fit(X_train, y_train)
pred = clf.predict(X_test)
print("accuracy:", round(accuracy_score(y_test, pred), 3))
print("confusion:\\n", confusion_matrix(y_test, pred))
print()
print(classification_report(y_test, pred, digits=3))Rows of the matrix are the true class. Columns are the predicted class. The diagonal is correct.
Plot
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
X, y = make_classification(n_samples=200, n_features=4, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
clf = LogisticRegression(max_iter=200)
clf.fit(X_train, y_train)
cm = confusion_matrix(y_test, clf.predict(X_test))
print(cm)
fig, ax = plt.subplots()
image = ax.imshow(cm, cmap="Blues")
fig.colorbar(image, ax=ax)
ax.set_xlabel("predicted")
ax.set_ylabel("true")
ax.set_xticks([0, 1], ["0", "1"])
ax.set_yticks([0, 1], ["0", "1"])
for i in range(2):
for j in range(2):
ax.text(j, i, str(cm[i, j]), ha="center", va="center")
ax.set_title("Confusion matrix")
plt.show()Tip
When one class is rare, a model that always predicts the majority can look “accurate.” Read recall for the rare class in the report.