Evaluating Models: Confusion Matrix, Precision, Recall & F1

Deep Learning with Keras and TensorFlow 11 min min read Updated: Nov 16, 2026 Intermediate
Evaluating Models: Confusion Matrix, Precision, Recall & F1
Intermediate Topic 9 of 9

Why Accuracy is Not Enough

Imagine a test for a rare disease that only 1 in 100 people have. A lazy model that says healthy to everyone is 99 percent accurate, but it never finds a sick person. That is why we need other measures.

The Confusion Matrix

A confusion matrix counts how many samples were predicted correctly and incorrectly. For a yes or no problem, there are four cells.

Predicted: YesPredicted: No
Actual: YesTrue Positive (TP)False Negative (FN)
Actual: NoFalse Positive (FP)True Negative (TN)

Precision, Recall and F1

MetricQuestion it answersFormula
AccuracyHow many predictions were right overall?(TP + TN) / all
PrecisionWhen the model says yes, how often is it right?TP / (TP + FP)
RecallOf all real yes cases, how many did we find?TP / (TP + FN)
F1 scoreA balance between precision and recall2 x P x R / (P + R)
When to use which: For medical tests and fraud detection, recall is vital because missing a case is costly. For spam filters, precision matters because blocking a good email is annoying.

Doing It with Code

python import numpy as np from sklearn.metrics import confusion_matrix, classification_report # Get predictions from a trained multi-class model probs = model.predict(x_test) y_pred = np.argmax(probs, axis=1) print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred))

Plot the Confusion Matrix

python import matplotlib.pyplot as plt from sklearn.metrics import ConfusionMatrixDisplay ConfusionMatrixDisplay.from_predictions(y_test, y_pred, cmap="Blues") plt.show()

The diagonal shows the correct predictions. Bright cells away from the diagonal show which classes the model confuses, for example a 4 predicted as a 9.

Binary Models and Thresholds

python probs = model.predict(x_test).ravel() # sigmoid outputs y_pred = (probs > 0.5).astype(int) # default threshold y_pred_strict = (probs > 0.8).astype(int) # fewer false positives, more false negatives

Changing the threshold trades precision against recall.

Metrics Directly in Keras

python model.compile( optimizer="adam", loss="binary_crossentropy", metrics=["accuracy", keras.metrics.Precision(name="precision"), keras.metrics.Recall(name="recall"), keras.metrics.AUC(name="auc")] )

Conclusion

A good data scientist never trusts accuracy alone. Check the confusion matrix and use precision, recall and F1, especially when the classes are not balanced.

Quick Summary: Accuracy can mislead. Use the confusion matrix, precision, recall and F1, and adjust the threshold for your goal.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators