Build the Model for Fashion MNIST dataset Using TensorFlow in Python
Last Updated :
23 Jul, 2025
The primary objective will be to build a classification model which will be able to identify the different categories of the fashion industry from the Fashion MNIST dataset using Tensorflow and Keras
To complete our objective, we will create a CNN model to identify the image categories and train it on the dataset. We are using deep learning as a method of choice since the dataset consists of images, and CNN's have been the choice of algorithm for image classification tasks. We will use Keras to create CNN and Tensorflow for data manipulation tasks.
The task will be divided into three steps data analysis, model training and prediction. Let us start with data analysis.
Data Analysis
Step 1: Importing the required libraries
We will first import all the required libraries to complete our objective. To show images, we will use matplotlib, and for array manipulations, we will use NumPy. Tensorflow and Keras will be used for ML and deep learning stuff.
Python3
# To load the mnist data
from keras.datasets import fashion_mnist
from tensorflow.keras.models import Sequential
# importing various types of hidden layers
from tensorflow.keras.layers import Conv2D, MaxPooling2D,\
Dense, Flatten
# Adam optimizer for better LR and less loss
from tensorflow.keras.optimizers import Adam
import matplotlib.pyplot as plt
import numpy as np
The Fashion MNIST dataset is readily made available in the keras.dataset library, so we have just imported it from there.
The dataset consists of 70,000 images, of which 60,000 are for training, and the remaining are for testing purposes. The images are in grayscale format. Each image consists of 28x28 pixels, and the number of categories is 10. Hence there are 10 labels available to us, and they are as follows:
- T-shirt/top
- Trouser
- Pullover
- Dress
- Coat
- Sandal
- Shirt
- Sneaker
- Bag
- Ankle boot
Step 2: Loading data and auto-splitting it into training and test
We will load out data using the load_dataset function. It will return us with the training and testing dataset split mentioned above.
Python3
# Split the data into training and testing
(trainX, trainy), (testX, testy) = fashion_mnist.load_data()
# Print the dimensions of the dataset
print('Train: X = ', trainX.shape)
print('Test: X = ', testX.shape)
The train contains data from 60,000 images, and the test contains data from 10,000 images
Step 3: Visualise the data
As we have loaded the data, we will visualize some sample images from it. To view the images, we will use the iterator to iterate and, in Matplotlib plot the images.
Python3
for i in range(1, 10):
# Create a 3x3 grid and place the
# image in ith position of grid
plt.subplot(3, 3, i)
# Insert ith image with the color map 'grap'
plt.imshow(trainX[i], cmap=plt.get_cmap('gray'))
# Display the entire plot
plt.show()

With this, we have come to the end of the data analysis. Now we will move forward to model training.
Model training
Step 1: Creating a CNN architecture
We will create a basic CNN architecture from scratch to classify the images. We will be using 3 convolution layers along with 3 max-pooling layers. At last, we will add a softmax layer of 10 nodes as we have 10 labels to be identified.
Python3
def model_arch():
models = Sequential()
# We are learning 64
# filters with a kernal size of 5x5
models.add(Conv2D(64, (5, 5),
padding="same",
activation="relu",
input_shape=(28, 28, 1)))
# Max pooling will reduce the
# size with a kernal size of 2x2
models.add(MaxPooling2D(pool_size=(2, 2)))
models.add(Conv2D(128, (5, 5), padding="same",
activation="relu"))
models.add(MaxPooling2D(pool_size=(2, 2)))
models.add(Conv2D(256, (5, 5), padding="same",
activation="relu"))
models.add(MaxPooling2D(pool_size=(2, 2)))
# Once the convolutional and pooling
# operations are done the layer
# is flattened and fully connected layers
# are added
models.add(Flatten())
models.add(Dense(256, activation="relu"))
# Finally as there are total 10
# classes to be added a FCC layer of
# 10 is created with a softmax activation
# function
models.add(Dense(10, activation="softmax"))
return models
Now we will see the model summary. To do that, we will first compile our model and set out loss to sparse categorical crossentropy and metrics as sparse categorical accuracy.
Python3
model = model_arch()
model.compile(optimizer=Adam(learning_rate=1e-3),
loss='sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'])
model.summary()
Model summary
Step 2: Train the data on the model
As we have compiled the model, we will now train our model. To do this, we will use mode.fit() function and set the epochs to 10. We will also perform a validation split of 33% to get better test accuracy and have a minimum loss.
Python3
history = model.fit(
trainX.astype(np.float32), trainy.astype(np.float32),
epochs=10,
steps_per_epoch=100,
validation_split=0.33
)
Step 3: Save the model
We will now save the model in the .h5 format so it can be bundled with any web framework or any other development domain.
Python3
model.save_weights('./model.h5', overwrite=True)
Step 4: Plotting the training and loss functions
Training and loss functions are important functions in any ML project. they tell us how well the model performs under how many epochs and how much time the model takes actually to converge.
Python3
# Accuracy vs Epoch plot
plt.plot(history.history['sparse_categorical_accuracy'])
plt.plot(history.history['val_sparse_categorical_accuracy'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
Output:

Python3
# Loss vs Epoch plot
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model Accuracy')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
Output:

Prediction
Now we will use model.predict() to get the prediction. It will return an array of size 10, consisting of the labels' probabilities. The max probability of the label will be the answer.
Python3
# There are 10 output labels for the
# Fashion MNIST dataset
labels = ['t_shirt', 'trouser', 'pullover',
'dress', 'coat', 'sandal', 'shirt',
'sneaker', 'bag', 'ankle_boots']
# Make a prediction
predictions = model.predict(testX[:1])
label = labels[np.argmax(predictions)]
print(label)
plt.imshow(testX[:1][0])
plt.show()
Output:
Similar Reads
Deep Learning Tutorial Deep Learning is a subset of Artificial Intelligence (AI) that helps machines to learn from large datasets using multi-layered neural networks. It automatically finds patterns and makes predictions and eliminates the need for manual feature extraction. Deep Learning tutorial covers the basics to adv
5 min read
Deep Learning Basics
Introduction to Deep LearningDeep Learning is transforming the way machines understand, learn and interact with complex data. Deep learning mimics neural networks of the human brain, it enables computers to autonomously uncover patterns and make informed decisions from vast amounts of unstructured data. How Deep Learning Works?
7 min read
Artificial intelligence vs Machine Learning vs Deep LearningNowadays many misconceptions are there related to the words machine learning, deep learning, and artificial intelligence (AI), most people think all these things are the same whenever they hear the word AI, they directly relate that word to machine learning or vice versa, well yes, these things are
4 min read
Deep Learning Examples: Practical Applications in Real LifeDeep learning is a branch of artificial intelligence (AI) that uses algorithms inspired by how the human brain works. It helps computers learn from large amounts of data and make smart decisions. Deep learning is behind many technologies we use every day like voice assistants and medical tools.This
3 min read
Challenges in Deep LearningDeep learning, a branch of artificial intelligence, uses neural networks to analyze and learn from large datasets. It powers advancements in image recognition, natural language processing, and autonomous systems. Despite its impressive capabilities, deep learning is not without its challenges. It in
7 min read
Why Deep Learning is ImportantDeep learning has emerged as one of the most transformative technologies of our time, revolutionizing numerous fields from computer vision to natural language processing. Its significance extends far beyond just improving predictive accuracy; it has reshaped entire industries and opened up new possi
5 min read
Neural Networks Basics
What is a Neural Network?Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamental
12 min read
Types of Neural NetworksNeural networks are computational models that mimic the way biological neural networks in the human brain process information. They consist of layers of neurons that transform the input data into meaningful outputs through a series of mathematical operations. In this article, we are going to explore
7 min read
Layers in Artificial Neural Networks (ANN)In Artificial Neural Networks (ANNs), data flows from the input layer to the output layer through one or more hidden layers. Each layer consists of neurons that receive input, process it, and pass the output to the next layer. The layers work together to extract features, transform data, and make pr
4 min read
Activation functions in Neural NetworksWhile building a neural network, one key decision is selecting the Activation Function for both the hidden layer and the output layer. It is a mathematical function applied to the output of a neuron. It introduces non-linearity into the model, allowing the network to learn and represent complex patt
8 min read
Feedforward Neural NetworkFeedforward Neural Network (FNN) is a type of artificial neural network in which information flows in a single direction i.e from the input layer through hidden layers to the output layer without loops or feedback. It is mainly used for pattern recognition tasks like image and speech classification.
6 min read
Backpropagation in Neural NetworkBack Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Deep Learning Models
Deep Learning Frameworks
TensorFlow TutorialTensorFlow is an open-source machine-learning framework developed by Google. It is written in Python, making it accessible and easy to understand. It is designed to build and train machine learning (ML) and deep learning models. It is highly scalable for both research and production.It supports CPUs
2 min read
Keras TutorialKeras high-level neural networks APIs that provide easy and efficient design and training of deep learning models. It is built on top of powerful frameworks like TensorFlow, making it both highly flexible and accessible. Keras has a simple and user-friendly interface, making it ideal for both beginn
3 min read
PyTorch TutorialPyTorch is an open-source deep learning framework designed to simplify the process of building neural networks and machine learning models. With its dynamic computation graph, PyTorch allows developers to modify the networkâs behavior in real-time, making it an excellent choice for both beginners an
7 min read
Caffe : Deep Learning FrameworkCaffe (Convolutional Architecture for Fast Feature Embedding) is an open-source deep learning framework developed by the Berkeley Vision and Learning Center (BVLC) to assist developers in creating, training, testing, and deploying deep neural networks. It provides a valuable medium for enhancing com
8 min read
Apache MXNet: The Scalable and Flexible Deep Learning FrameworkIn the ever-evolving landscape of artificial intelligence and deep learning, selecting the right framework for building and deploying models is crucial for performance, scalability, and ease of development. Apache MXNet, an open-source deep learning framework, stands out by offering flexibility, sca
6 min read
Theano in PythonTheano is a Python library that allows us to evaluate mathematical operations including multi-dimensional arrays efficiently. It is mostly used in building Deep Learning Projects. Theano works way faster on the Graphics Processing Unit (GPU) rather than on the CPU. This article will help you to unde
4 min read
Model Evaluation
Deep Learning Projects