Learn Classification of clothing images using TensorFlow in Python

Hello Everyone! In this post, let’s take a look at the Classification of various clothing images with the help of TensorFlow in Python.

Introduction to Classification Problem

fashionWe live in the age of Instagram, YouTube, and Twitter. It is very important for people nowadays to know how to classify clothing into various categories especially models and celebrities.

Building the Project

fashion flowchart

Step 1: Importing Modules

The first step in every project is to import all the required modules.

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

Step 2: Loading and pre-processing of Data

The code below includes the data loading:

fashion_data=tf.keras.datasets.fashion_mnist

Step 3: Training and Testing Data Split

The code includes splitting the data into training and testing and also normalizing the data.

(inp_train,out_train),(inp_test,out_test)=fashion_data.load_data()
inp_train = inp_train/255.0
inp_test = inp_test/255.0
print("Shape of Input Training Data: ", inp_train.shape)
print("Shape of Output Training Data: ", out_train.shape)
print("Shape of Input Testing Data: ", inp_test.shape)
print("Shape of Output Testing Data: ", out_test.shape)

The final shapes of all the x and y train, as well as test data, is as follows:

Shape of Input Training Data:  (60000, 28, 28)
Shape of Output Training Data:  (60000,)
Shape of Input Testing Data:  (10000, 28, 28)
Shape of Output Testing Data:  (10000,)

Step 4: Data Visualization

The code to visualize the initial data is as follows:

plt.figure(figsize=(10,10))
for i in range(100):
    plt.subplot(10,10,i+1)
    plt.imshow(inp_train[i])
    plt.xticks([])
    plt.yticks([])
    plt.xlabel(out_train[i])
    plt.tight_layout()
plt.show()

The result of the visualization is shown below:

initial_data_visual

Step 5: Changing the labels to actual names

Now you can see in the previous visualization the labels are all numbers. But we want the labels to be names, hence we now work on that and visualize the data in the following code:

Labels=['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat','Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
plt.figure(figsize=(10,10))
for i in range(100):
    plt.subplot(10,10,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.imshow(inp_train[i], cmap=plt.cm.binary)
    plt.xlabel(Labels[out_train[i]])
    plt.tight_layout()
plt.show()

The new visualization is as follows:

data_label_visual

You can see now that the visualization is now more understandable. Let’s move on to the main building of the model.

Step 6: Building, Compiling, Training the model

The code for the building, compiling, and training of the TensorFlow and Keras model is shown below:

my_model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10)
])
my_model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
my_model.fit(inp_train, out_train, epochs=20)

The result of the training at each epoch is as follows:

Epoch 1/20
1875/1875 [==============================] - 2s 998us/step - loss: 0.6246 - accuracy: 0.7832
Epoch 2/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.3835 - accuracy: 0.8612
Epoch 3/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.3323 - accuracy: 0.8773
Epoch 4/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.3123 - accuracy: 0.8850
Epoch 5/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.2943 - accuracy: 0.8907
Epoch 6/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.2745 - accuracy: 0.8966
Epoch 7/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.2643 - accuracy: 0.9020
Epoch 8/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.2550 - accuracy: 0.9066
Epoch 9/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.2477 - accuracy: 0.9076
Epoch 10/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.2333 - accuracy: 0.9127
Epoch 11/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.2277 - accuracy: 0.9131
Epoch 12/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.2131 - accuracy: 0.9212
Epoch 13/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.2121 - accuracy: 0.9199
Epoch 14/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.2071 - accuracy: 0.9231
Epoch 15/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.1977 - accuracy: 0.9275
Epoch 16/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.1936 - accuracy: 0.9265
Epoch 17/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.1906 - accuracy: 0.9292
Epoch 18/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.1813 - accuracy: 0.9332
Epoch 19/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.1812 - accuracy: 0.9332
Epoch 20/20
1875/1875 [==============================] - 2s 1ms/step - loss: 0.1738 - accuracy: 0.9352
<tensorflow.python.keras.callbacks.History at 0x1fd9da98898>

Step 7: Checking the final loss and accuracy

The code to check the accuracy is as follows:

loss, accuracy = my_model.evaluate(inp_test,out_test,verbose=2)
print('\nAccuracy:',accuracy*100)

The final accuracy we get after the whole processing of our model is 88.8% which is pretty good.

Step8: Make Predictions

We come to make the final predictions and the code is as follows:

prob=tf.keras.Sequential([my_model,tf.keras.layers.Softmax()])
pred=prob.predict(inp_test)

Step 9: Visualizing the final predictions

We visualize the first 20 images. The code for the same is as follows:

plt.figure(figsize=(20,20))
for i in range(20):
    true_label,image = out_test[i],inp_test[i]
    pred_label = np.argmax(pred[i])
    plt.subplot(10,10,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.imshow(image, cmap=plt.cm.binary)
    if pred_label == true_label:
        color = 'green'
        label="Correct Prediction!"
    else:
        color = 'red'
        label="Wrong Prediction!"
    plt.tight_layout()
    plt.title(label,color=color)
    plt.xlabel(" {} -> {} ".format(Labels[true_label],Labels[pred_label]))

The result of the visualization is:

predictions_visual

Conclusion

Thank you for reading the post. Keep reading to learn more. You can find the code for the project here.

Some Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *