0
0
TensorFlowml~5 mins

Confusion matrix visualization in TensorFlow

Choose your learning style9 modes available
Introduction

A confusion matrix helps us see how well a model is doing by showing where it gets things right or wrong.

When you want to check how many times your model guessed each class correctly or incorrectly.
When you need to understand which classes your model confuses the most.
When you want a clear picture of your model's performance beyond just accuracy numbers.
Syntax
TensorFlow
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

cm = tf.math.confusion_matrix(labels, predictions)

plt.imshow(cm, cmap='Blues')
plt.colorbar()
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('Confusion Matrix')
plt.show()

labels are the true class values.

predictions are the model's predicted class values.

Examples
This creates a confusion matrix for 3 classes with some correct and incorrect predictions.
TensorFlow
labels = [0, 1, 2, 2, 0]
predictions = [0, 2, 1, 2, 0]
cm = tf.math.confusion_matrix(labels, predictions)
This shows the confusion matrix with a green color map.
TensorFlow
plt.imshow(cm, cmap='Greens')
plt.colorbar()
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('Confusion Matrix')
plt.show()
Sample Model

This program calculates the confusion matrix from true labels and predictions, prints it, and then shows it as a colored grid.

TensorFlow
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

# True labels for 5 samples
labels = [0, 1, 2, 2, 0]
# Model predictions for the same samples
predictions = [0, 2, 1, 2, 0]

# Compute confusion matrix
cm = tf.math.confusion_matrix(labels, predictions)

print('Confusion Matrix:')
print(cm.numpy())

# Plot confusion matrix
plt.imshow(cm, cmap='Blues')
plt.colorbar()
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('Confusion Matrix')
plt.show()
OutputSuccess
Important Notes

The confusion matrix shape depends on the number of classes.

Diagonal values show correct predictions; off-diagonal show mistakes.

Use color maps to make the matrix easier to read visually.

Summary

A confusion matrix shows how many times each class was predicted correctly or wrongly.

It helps understand model errors beyond just accuracy.

TensorFlow's tf.math.confusion_matrix makes it easy to create this matrix.