How to Classify Fashion MNIST Using Deep Learning with Keras in Python?
Share
Condition for Classifying Handwritten Digits Using Deep Learning with Keras in Python
Description: This code uses a Convolutional Neural Network (CNN) to classify images from the Fashion MNIST dataset into 10 categories. The model is trained, evaluated with classification metrics, and visualized using a confusion matrix. It performs image preprocessing, model building, and evaluation to assess accuracy and performance.
Step-by-Step Process
Step1: Essential libraries like TensorFlow, Matplotlib, and Scikit-learn are imported for model building, visualization, and evaluation.
Step2: The Fashion MNIST dataset is loaded using TensorFlow's built-in function, providing images and labels for training and testing.
Step3: A function is defined to plot a set of sample images from the training data, showing labels on the images to understand the data.
Step4: The pixel values of the images are normalized by dividing by 255 to scale them to a range of 0 to 1.
Step5: The image data is reshaped to include a channel dimension, converting it from (28, 28) to (28, 28, 1) for compatibility with the CNN.
Step6: A Convolutional Neural Network is defined with two convolutional layers, max-pooling, flattening, and fully connected layers with ReLU activations.
Step7: The model is compiled using Adam optimizer, sparse categorical cross-entropy loss, and accuracy as the evaluation metric.
Step8: The CNN model is trained on the training set for 10 epochs with a batch size of 16, using the test set for validation.
Step9: After training, predictions are made on the test set, with each output class predicted using argmax.
Step10: Classification performance is evaluated using metrics like accuracy, F1 score, precision, and recall, and the confusion matrix is visualized with a heatmap.
Sample Code
#Import Necessary Libraries
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense
from tensorflow.keras.models import Model
from sklearn.metrics import (classification_report, confusion_matrix, accuracy_score,
f1_score, recall_score, precision_score)
# Build the model
cnn_model = Model(inputs=inputs, outputs=output_layer)
# Compile the model with Adam optimizer and binary crossentropy loss function
cnn_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
return cnn_model
model = CNN_model((x_train.shape[1],x_train.shape[2],1))