How can Tensorflow be used with Fashion MNIST dataset so that the trained model is used to predict a different image in Python?

TensorFlow is a machine learning framework provided by Google. It is an open-source framework used with Python to implement algorithms, deep learning applications and much more. It uses optimization techniques that help perform complicated mathematical operations quickly through NumPy and multi-dimensional arrays called tensors.

The Fashion MNIST dataset contains grayscale images of clothing items from 10 different categories. Each image is 28x28 pixels and there are over 70,000 images in total. This dataset is commonly used for training image classification models.

Installation

Install TensorFlow using pip ?

pip install tensorflow

Complete Example - Training and Predicting

Here's a complete example that trains a model on Fashion MNIST and uses it to predict a new image ?

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

# Load and prepare the Fashion MNIST dataset
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

# Define class names for Fashion MNIST
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

# Normalize pixel values to be between 0 and 1
train_images = train_images / 255.0
test_images = test_images / 255.0

# Build the model
model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10)
])

# Compile the model
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

# Train the model (using fewer epochs for demo)
model.fit(train_images, train_labels, epochs=5, verbose=0)

# Create probability model for predictions
probability_model = tf.keras.Sequential([model, 
                                       tf.keras.layers.Softmax()])

print("Model training completed!")
Model training completed!

Making Predictions on a Single Image

Now we'll use the trained model to predict a single image from the test dataset ?

# Take an image from the test data
img_index = 26
img = test_images[img_index]
print("The dimensions of the image are:")
print(img.shape)

# Add the image to a batch (model expects a batch of images)
img_batch = np.expand_dims(img, 0)
print("The dimensions after adding to batch:")
print(img_batch.shape)

# Make prediction
predictions = probability_model.predict(img_batch)
print("The prediction probabilities are:")
print(predictions[0])

# Get the predicted class
predicted_class = np.argmax(predictions[0])
actual_class = test_labels[img_index]

print(f"Predicted class: {predicted_class} ({class_names[predicted_class]})")
print(f"Actual class: {actual_class} ({class_names[actual_class]})")
The dimensions of the image are:
(28, 28)
The dimensions after adding to batch:
(1, 28, 28)
The prediction probabilities are:
[8.0459216e-07 1.7074371e-09 2.6175227e-02 1.8855806e-07 1.7909618e-01
 2.1126857e-06 7.9472500e-01 7.5104166e-11 4.7921480e-07 1.6657851e-10]
Predicted class: 6 (Shirt)
Actual class: 6 (Shirt)

Key Steps Explained

Data Preparation: The images are normalized to values between 0 and 1 for better training performance.

Model Architecture: A simple neural network with a flatten layer, one hidden layer with 128 neurons, and an output layer with 10 neurons (one for each clothing category).

Batch Processing: The expand_dims function adds a batch dimension because TensorFlow models expect batches of images, even for single predictions.

Probability Model: We add a Softmax layer to convert the raw model outputs into probabilities that sum to 1.

Understanding the Output

The prediction returns an array of 10 probabilities, one for each clothing category. The highest probability indicates the model's prediction. In this example, index 6 (Shirt) has the highest probability at approximately 0.795 or 79.5% confidence.

Conclusion

TensorFlow makes it easy to train neural networks on Fashion MNIST and use them for predictions. The key steps are normalizing data, building a model, training it, and using expand_dims to format single images for batch prediction.

Updated on: 2026-03-25T15:36:06+05:30

251 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements