Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can Tensorflow be used to evaluate a CNN model using Python?
A convolutional neural network (CNN) can be evaluated using TensorFlow's evaluate() method. This method takes the test data as parameters and returns loss and accuracy metrics. Before evaluation, it's common to visualize the training progress using matplotlib to plot accuracy versus epochs.
Read More: What is TensorFlow and how Keras work with TensorFlow to create Neural Networks?
Convolutional neural networks have been used to produce great results for specific problems, such as image recognition and computer vision tasks.
Prerequisites
This example assumes you have a trained CNN model and prepared test data. We're using Google Colaboratory which provides free access to GPUs and comes with TensorFlow pre-installed.
Plotting Training Progress
First, let's visualize the training accuracy over epochs to understand model performance ?
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
import numpy as np
# Sample training history (normally this comes from model.fit())
history_dict = {
'accuracy': [0.6, 0.65, 0.68, 0.70, 0.705],
'val_accuracy': [0.58, 0.62, 0.65, 0.67, 0.68]
}
print("Plotting accuracy versus epoch")
plt.figure(figsize=(8, 6))
plt.plot(history_dict['accuracy'], label='Training accuracy')
plt.plot(history_dict['val_accuracy'], label='Validation accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
plt.title('Model Accuracy Over Epochs')
plt.grid(True)
plt.show()
Plotting accuracy versus epoch
Evaluating the CNN Model
Now let's evaluate the trained model on test data to get final performance metrics ?
# Sample test data (normally loaded from your dataset)
test_images = np.random.random((1000, 32, 32, 3)) # 1000 test images
test_labels = np.random.randint(0, 10, (1000,)) # 1000 test labels
# Create a simple CNN model for demonstration
model = keras.Sequential([
keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
keras.layers.MaxPooling2D((2, 2)),
keras.layers.Conv2D(64, (3, 3), activation='relu'),
keras.layers.MaxPooling2D((2, 2)),
keras.layers.Conv2D(64, (3, 3), activation='relu'),
keras.layers.Flatten(),
keras.layers.Dense(64, activation='relu'),
keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
print("The model is being evaluated")
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print("The accuracy of the model is:")
print(test_acc)
The model is being evaluated 32/32 - 1s - loss: 2.3026 - accuracy: 0.1000 The accuracy of the model is: 0.10000000149011612
Understanding the Output
The evaluate() method returns two values ?
- test_loss − The loss value on test data
- test_acc − The accuracy percentage on test data
- verbose=2 − Controls output verbosity (0=silent, 1=progress bar, 2=one line per epoch)
Complete Evaluation Workflow
Here's a typical workflow for evaluating a CNN model ?
# 1. Load and preprocess test data
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
x_test = x_test / 255.0 # Normalize pixel values
# 2. Load trained model
model = tf.keras.models.load_model('my_cnn_model.h5')
# 3. Evaluate model
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=1)
# 4. Display results
print(f"Test accuracy: {test_acc:.4f}")
print(f"Test loss: {test_loss:.4f}")
# 5. Make predictions for analysis
predictions = model.predict(x_test[:10])
predicted_classes = np.argmax(predictions, axis=1)
Key Points
| Method | Purpose | Returns |
|---|---|---|
model.evaluate() |
Calculate loss and metrics on test data | Loss and accuracy values |
model.predict() |
Generate predictions for input data | Prediction probabilities |
plt.plot() |
Visualize training progress | Training plots |
Conclusion
Use model.evaluate() to assess CNN performance on test data, returning loss and accuracy metrics. Combine with matplotlib visualization to analyze training progress and model convergence over epochs.
