Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Classify Fashion MNIST Using Deep Learning with Keras in Python?

Fashion MNIST Classification with Keras and Deep Learning in Python

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)

     import warnings
     warnings.filterwarnings("ignore")

     import seaborn as sns

    # Load the Fashion MNIST dataset
     fashion_mnist = tf.keras.datasets.fashion_mnist
     (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()

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

    # Function to plot sample images
     def plot_sample_images(images, labels, class_names, rows=3, cols=5):
      plt.figure(figsize=(10, 7))
      for i in range(rows * cols):
       plt.subplot(rows, cols, i + 1)
       plt.imshow(images[i], cmap="gray")
       plt.title(class_names[labels[i]])
       plt.axis("off")
      plt.tight_layout()
      plt.show()

    # Visualize the first 15 samples from the training set
     plot_sample_images(x_train, y_train, class_names)

    #data_normalization
     x_train = x_train/255
     x_test = x_test/255

     x_train = x_train.reshape(x_train.shape[0],x_train.shape[1],x_train.shape[2],1)
     x_test = x_test.reshape(x_test.shape[0],x_test.shape[1],x_test.shape[2],1)

    def CNN_model(input_shape):
      # Input layer (for image data, input_shape includes height, width, and channels)
      inputs = Input(shape=input_shape)

      # Convolutional layers
      conv1 = Conv2D(32, (3, 3), activation='relu', padding='same')(inputs)
      pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)

      conv2 = Conv2D(64, (3, 3), activation='relu', padding='same')(pool1)
      pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)

      # Flatten the 2D feature maps into a 1D feature vector
      flatten = Flatten()(pool2)

      # Fully connected (Dense) layers
      dense1 = Dense(64, activation='relu')(flatten)
      dense2 = Dense(32,activation='relu')(dense1)
      output_layer = Dense(10, activation='softmax')(dense2)

      # 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))

    model.fit(x_train,y_train,batch_size=16,epochs=10,validation_data=(x_test,y_test))

    y_pred = model.predict(x_test)
     y_pred = [np.argmax(i) for i in y_pred]

    print("___Performance_Metrics___\n")
    print('Classification_Report:\n',classification_report(y_test, y_pred))
    print('Confusion_Matrix:\n',confusion_matrix(y_test, y_pred))
    print('\n')
    print('Accuracy_Score: ',accuracy_score(y_test, y_pred))
    print('F1_Score (macro): ', f1_score(y_test, y_pred, average='macro'))
    print('Recall_Score (macro): ', recall_score(y_test, y_pred, average='macro'))
    print('Precision_Score (macro): ', precision_score(y_test, y_pred, average='macro'))

    #Plot Confusion Matrix
     # Compute confusion matrix
     cm = confusion_matrix(y_test, y_pred)

     # Plot confusion matrix using seaborn heatmap
     plt.figure(figsize=(6,6))
     sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=[
      "T-shirt/top", "Trouser", "Pullover", "Dress", "Coat",
      "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"
     ], yticklabels=[
      "T-shirt/top", "Trouser", "Pullover", "Dress", "Coat",
      "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"
     ])
     plt.title('Confusion Matrix')
     plt.xlabel('Predicted Label')
     plt.ylabel('True Label')
     plt.show()
Screenshots
  • Fashion MNIST Classification