0
0
TensorFlowml~5 mins

Classification reports in TensorFlow

Choose your learning style9 modes available
Introduction

A classification report helps us see how well our model is doing by showing simple numbers about its guesses.

After training a model to check how well it predicts different categories.
When comparing two or more models to pick the best one.
To find out if the model is making more mistakes on some categories than others.
When you want a quick summary of precision, recall, and accuracy for your model.
Syntax
TensorFlow
from sklearn.metrics import classification_report

report = classification_report(true_labels, predicted_labels)
print(report)

You need to have the true labels and the predicted labels from your model.

This function is from the sklearn library, which works well with TensorFlow outputs.

Examples
Basic example showing how to print a classification report for three classes.
TensorFlow
from sklearn.metrics import classification_report

true_labels = [0, 1, 2, 2, 1]
predicted_labels = [0, 2, 2, 2, 1]

print(classification_report(true_labels, predicted_labels))
Example with named classes for easier reading.
TensorFlow
from sklearn.metrics import classification_report

true_labels = [0, 1, 1, 0]
predicted_labels = [0, 0, 1, 0]

print(classification_report(true_labels, predicted_labels, target_names=['Cat', 'Dog']))
Sample Model

This program trains a tiny model on a small dataset, predicts the classes, and prints a classification report showing precision, recall, and f1-score for each class.

TensorFlow
import tensorflow as tf
from sklearn.metrics import classification_report
import numpy as np

# Create a simple dataset
x_train = np.array([[0., 0.], [1., 1.], [0., 1.], [1., 0.]])
y_train = np.array([0, 1, 1, 0])

# Build a simple model
model = tf.keras.Sequential([
    tf.keras.layers.Dense(2, activation='softmax', input_shape=(2,))
])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Train the model
model.fit(x_train, y_train, epochs=10, verbose=0)

# Predict classes
pred_probs = model.predict(x_train)
pred_labels = np.argmax(pred_probs, axis=1)

# Print classification report
report = classification_report(y_train, pred_labels, target_names=['Class 0', 'Class 1'])
print(report)
OutputSuccess
Important Notes

The classification report shows precision, recall, f1-score, and support for each class.

Precision means how many selected items are relevant, recall means how many relevant items are selected.

F1-score balances precision and recall into one number.

Summary

Classification reports give a clear summary of model performance on each class.

They help find which classes the model predicts well or poorly.

Use them after predictions to understand your model better.