how to create confusion matrix for classification in tensorflow
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
A confusion matrix shows how a classification model's predictions compare to actual labels, breaking down true positives, false positives, true negatives, and false negatives for each class. In TensorFlow, use tf.math.confusion_matrix(labels, predictions) to compute it. For visualization, pass the result to seaborn.heatmap() or sklearn.metrics.ConfusionMatrixDisplay. The matrix helps identify which classes the model confuses most, guiding targeted improvements in data collection and model architecture.
Basic Confusion Matrix with TensorFlow
Each row represents the actual class and each column represents the predicted class. Row 0, column 0 (value 3) means all three class-0 samples were correctly predicted. Row 2, column 0 (value 1) means one class-2 sample was incorrectly predicted as class 0.
From Model Predictions to Confusion Matrix
For multi-class classification with softmax output, apply np.argmax() to convert probability vectors to class indices before computing the confusion matrix.
Binary Classification
For binary classification, the 2x2 matrix positions are: top-left = True Negatives, top-right = False Positives, bottom-left = False Negatives, bottom-right = True Positives.
Visualizing with Seaborn
sns.heatmap with annot=True displays the counts in each cell. Use fmt='d' for integer formatting or fmt='.2f' for normalized values.
Normalized Confusion Matrix
Normalization reveals performance per class regardless of class imbalance. A raw count of 50 correct predictions for class A means different things if class A has 50 samples (100%) versus 500 samples (10%).
Computing Metrics from Confusion Matrix
Using sklearn for Display (with TF Model)
Common Pitfalls
- Forgetting
argmaxfor softmax output:model.predict()returns probability vectors for multi-class models. Passing raw probabilities totf.math.confusion_matrixproduces wrong results. Applynp.argmax(predictions, axis=1)first to convert to class indices. - Misinterpreting row vs column: In TensorFlow's confusion matrix, rows are actual labels and columns are predictions. Confusing this reverses the meaning of false positives and false negatives, leading to incorrect precision and recall calculations.
- Ignoring class imbalance: A model predicting the majority class for all samples can show high accuracy but the confusion matrix reveals zero predictions for minority classes. Always examine per-class recall (diagonal divided by row sum) to catch this.
- Using wrong
num_classes: Ifnum_classesis not specified, TensorFlow infers it from the data. If your test set happens to not contain class 4 out of 5 classes, the matrix will be 4x4 instead of 5x5. Always passnum_classesexplicitly. - Not normalizing for comparison: Comparing raw confusion matrices across datasets with different sizes is misleading. A model tested on 1,000 samples naturally shows larger counts than one tested on 100. Normalize by row to get comparable recall rates.
Summary
- Use
tf.math.confusion_matrix(y_true, y_pred)to compute the confusion matrix in TensorFlow - Convert softmax probabilities to class indices with
np.argmax()before computing the matrix - Rows represent actual labels, columns represent predicted labels
- Visualize with
seaborn.heatmap()orsklearn.metrics.ConfusionMatrixDisplay - Normalize by row to see per-class recall rates and identify confused class pairs
- Extract precision, recall, and F1 directly from the matrix values (TP, FP, FN, TN)
Related reading
- How to create ensemble in tensorflow?
- How to create Keras model with optional inputs
- How to create only one copy of graph in tensorboard events file with custom tf.Estimator?
- How to create own dataset for using Mask-RCNN models from the Tensorflow Object Detection API?
- How to create dataset in the same format as the FSNS dataset?
- How to create dataset similar to cifar-10
- How to deal with batches with variable-length sequences in TensorFlow?
- How to deal with large2GB embedding lookup table in tensorflow?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.