0
0
TensorFlowml~5 mins

Confusion matrix analysis in TensorFlow

Choose your learning style9 modes available
Introduction

A confusion matrix helps us see how well a model guesses different groups. It shows where the model is right and where it makes mistakes.

Checking how well a model classifies emails as spam or not spam.
Evaluating a model that detects if a photo has a cat or a dog.
Understanding errors in a medical test that predicts illness or health.
Comparing different models to pick the best one for sorting fruits.
Seeing if a model confuses similar classes, like apples and pears.
Syntax
TensorFlow
tf.math.confusion_matrix(labels, predictions, num_classes=None, weights=None, dtype=tf.dtypes.int32, name=None)

labels: True class labels as a 1D tensor or array.

predictions: Predicted class labels as a 1D tensor or array.

Examples
Creates a confusion matrix for 3 classes with given true and predicted labels.
TensorFlow
cm = tf.math.confusion_matrix([0, 1, 2, 1], [0, 2, 1, 1])
Specifies number of classes explicitly to ensure matrix size.
TensorFlow
cm = tf.math.confusion_matrix(labels, predictions, num_classes=3)
Sample Model

This code compares true labels and predictions for 3 classes (0, 1, 2). It prints the confusion matrix showing counts of correct and wrong guesses.

TensorFlow
import tensorflow as tf

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

# Compute confusion matrix
conf_matrix = tf.math.confusion_matrix(true_labels, predictions, num_classes=3)

print('Confusion Matrix:')
print(conf_matrix.numpy())
OutputSuccess
Important Notes

The diagonal of the confusion matrix shows correct predictions.

Off-diagonal values show where the model made mistakes.

Use this matrix to calculate accuracy, precision, recall, and other metrics.

Summary

A confusion matrix helps visualize model performance by showing correct and wrong predictions.

It is useful for classification problems with multiple classes.

TensorFlow provides a simple function to create this matrix from labels and predictions.