Saturday, 18 September 2021

Image Classification Using Convolutional Neural Network (CNN)

 





Cifar10 Image Classification using Convolutional Neural Network 


Introduction:


    In this blog, I created image classification using convolutional neural network on Cifar10 small image classification data which I have implemented using TensorFlow and Keras.

    This blog offers you a step-by-step instruction guide with source code, so you can build your model. It is not designed to be a deep dive into model design, statistical analysis, improvement, and validation. If you want to learn more, please check out my blog site: Techy Scientists.

It contains the following parts:


  1. Setup your environment
  2. Build your image classification model
  3. Model Prediction


Setup your environment


   To run the program on your local computer, install the following required libraries, These libraries are 


  1.   python 3.8.0
  2.   numpy
  3.   pandas
  4.   matplotlib
  5.   tensorflow 2.0
  6.   keras 2.3.0


Build your image classification model


Step 1: Understand the data


  The first step of model prediction is to understand the data. It is more important to all machine learning and deep learning projects. You can find more information about the data, go to CIFAR10 small images classification dataset.






Step 2: Import the Packages


  Create a python file (for example model.py). After installed the required packages, import packages  in your python file.


import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import datasets, layers, models

Step 3: Import the data

    Next, import the data

cifar = datasets.cifar10

Step 4: Split the data
    
    We want to create a model, must have split it into training and testing. The model trained by training dataset and then apply the evaluation of model used by testing dataset.

(X_train, y_train), (X_test,y_test) = cifar.load_data()

Then, resize the data

y_train = y_train.reshape(-1,)
y_test = y_test.reshape(-1,)


Step 5: Normalize the data

    Then, Normalize the data values to the range [0, 1].

X_train = X_train / 255.0
X_test = X_test / 255.0


Step 6: Create Deep Learning Model

    We create model for image classification using convolutional neural network. It is type of deep learning networks. It is used for classification, segmentation and image processing problems. In this neural network, extract the features from input layer and perform mathematical convolutional operation. 


cnn = models.Sequential([
    layers.Conv2D(filters=32, 
    	kernel_size=(3, 3), 
        activation='relu', 
        input_shape=(32, 32, 3)),
    layers.MaxPooling2D((2, 2)),
    
    layers.Conv2D(filters=64, 
    	kernel_size=(3, 3), 
        activation='relu'),
    layers.MaxPooling2D((2, 2)),
    
    layers.Flatten(),
    layers.Dense(64, activation='relu'),
    layers.Dense(10, activation='softmax')
])


  •     Sequential - appropriate for a plain stack of layers where each layer has exactly one input tensor and one output tensor.
  •     Conv2D - Convolutional two dimensional layer.
  •     MaxPooling2D - pooling operation that calculate maximum value.
  •     Flatten -  matrix flatten to one dimensional array.
  •     Dense - fully connected neural network layer and it implement the operations.
  •     Activation - used through an activation  layer, or through the activation argument supported by all forward layers.


Step 7: Train the Model

    Now, we ready to train the model.

cnn.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
cnn.fit(X_train, y_train, epochs=10)
Out[]:
Epoch 1/10
1563/1563 [============] - 6s 4ms/step -
loss: 1.5192 - accuracy: 0.4548
Epoch 2/10
1563/1563 [============] - 6s 4ms/step -
loss: 1.1484 - accuracy: 0.6002
Epoch 3/10
1563/1563 [============] - 6s 4ms/step -
loss: 1.0044 - accuracy: 0.6497
Epoch 4/10
1563/1563 [============] - 6s 4ms/step -
loss: 0.9205 - accuracy: 0.6823
Epoch 5/10
1563/1563 [============] - 6s 4ms/step -
loss: 0.8628 - accuracy: 0.7020
Epoch 6/10
1563/1563 [============] - 6s 4ms/step -
loss: 0.8106 - accuracy: 0.7186
Epoch 7/10
1563/1563 [============] - 6s 4ms/step -
loss: 0.7674 - accuracy: 0.7340
Epoch 8/10
1563/1563 [============] - 6s 4ms/step -
loss: 0.7278 - accuracy: 0.7475
Epoch 9/10
1563/1563 [============] - 6s 4ms/step -
loss: 0.6919 - accuracy: 0.7611
Epoch 10/10
1563/1563 [============] - 6s 4ms/step -
loss: 0.6584 - accuracy: 0.7708


Step 8: Evaluate the Model

    Finally, We created the model and then evaluate it.

cnn.evaluate(X_test,y_test)
313/313 [==============] - 0s 1ms/step -
loss: 0.9197 - accuracy: 0.6942

[0.9197465777397156, 0.6941999793052673]


Model Prediction

    Finally, We predict the label of data on the basis of trained model. It returns the labels of the data passed as argument based upon the learned or trained data obtained from the model.

classes = ["airplane",
"automobile",
"bird",
"cat",
"deer",
"dog",
"frog",
"horse",
"ship",
"truck"]

    

Then, we predict the model using test dataset.

y_pred = cnn.predict(X_test)
       
Check that prediction,
y_classes = [np.argmax(element) for element in y_pred]
y_classes[:5]
Out[]:
[3, 8, 8, 0, 6]
def plot_sample(X, y, index):
    plt.figure(figsize = (15,2))
    plt.imshow(X[index])
    plt.xlabel(classes[y[index]])
plot_sample(X_test, y_test,3)


classes[y_classes[3]]
Out[]:
'airplane'

Conclusion:

     In summary, we created the image classification using convolutional neural network on fashion mnist data which I have implemented using TensorFlow and Keras. If you want to source code, check this GitHub linkImage classification.



No comments:

Post a Comment