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 make predictions for Fashion MNIST dataset 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 neural networks. TensorFlow uses NumPy and multi-dimensional arrays called tensors to perform complex mathematical operations efficiently.
The Fashion MNIST dataset contains grayscale images of clothing items from 10 different categories. Each image is 28x28 pixels and represents items like shirts, shoes, bags, and dresses. This dataset is commonly used for training image classification models.
Installation
Install TensorFlow using pip ?
pip install tensorflow
Making Predictions with a Trained Model
Once you have trained a model on the Fashion MNIST dataset, you can make predictions on test images. Here's how to create a prediction model and test it ?
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# Load Fashion MNIST dataset
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
# Normalize pixel values to 0-1 range
train_images = train_images / 255.0
test_images = test_images / 255.0
# Class names for Fashion MNIST
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# Create and train a simple 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)
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# Train the model (simplified for demo)
model.fit(train_images, train_labels, epochs=5, verbose=0)
# Create probability model with softmax layer
probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])
# Make predictions on test images
predictions = probability_model.predict(test_images[:10])
print("The predictions are being made")
print("First prediction probabilities:")
print(predictions[0])
# Get the predicted class
predicted_class = np.argmax(predictions[0])
print(f"Predicted class: {predicted_class} ({class_names[predicted_class]})")
print(f"Actual class: {test_labels[0]} ({class_names[test_labels[0]]})")
The predictions are being made First prediction probabilities: [1.3008227e-07 9.4930819e-10 2.0181861e-09 5.4944155e-10 3.8257373e-11 1.3896286e-04 1.4776078e-08 3.1724274e-03 9.4210514e-11 9.9668854e-01] Predicted class: 9 (Ankle boot) Actual class: 9 (Ankle boot)
Visualization Functions
You can create helper functions to visualize predictions and compare them with actual labels ?
def plot_image(i, predictions_array, true_label, img):
true_label, img = true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color)
def plot_value_array(i, predictions_array, true_label):
true_label = true_label[i]
plt.grid(False)
plt.xticks(range(10))
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')
# Example usage
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plot_image(0, predictions[0], test_labels, test_images)
plt.subplot(1, 2, 2)
plot_value_array(0, predictions[0], test_labels)
plt.tight_layout()
plt.show()
How It Works
The trained model outputs logits (raw prediction scores) for each class
A Softmax layer converts these logits into probabilities that sum to 1
The highest probability indicates the model's predicted class
The visualization functions help compare predicted vs. actual labels
Conclusion
TensorFlow makes it easy to create prediction models for Fashion MNIST using Sequential layers and Softmax activation. The probability outputs help interpret model confidence, while visualization functions provide clear comparisons between predictions and actual labels.
