Cainvas
Model Files
obj_class.h5
keras
Model
deepSea Compiled Models
obj_class.exe
deepSea
Ubuntu

Object Classifier Using CNN

Credit: AITS Cainvas Community

Photo by Cabify Design on Dribbble

In [1]:
!wget -N "https://cainvas-static.s3.amazonaws.com/media/user_data/cainvas-admin/obj.zip"
!unzip -qo obj.zip 
!rm obj.zip
--2021-07-14 16:18:59--  https://cainvas-static.s3.amazonaws.com/media/user_data/cainvas-admin/obj.zip
Resolving cainvas-static.s3.amazonaws.com (cainvas-static.s3.amazonaws.com)... 52.219.156.51
Connecting to cainvas-static.s3.amazonaws.com (cainvas-static.s3.amazonaws.com)|52.219.156.51|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 42553971 (41M) [application/x-zip-compressed]
Saving to: ‘obj.zip’

obj.zip             100%[===================>]  40.58M  95.8MB/s    in 0.4s    

2021-07-14 16:18:59 (95.8 MB/s) - ‘obj.zip’ saved [42553971/42553971]

Importing Libraries
In [2]:
import tensorflow as tf
from tensorflow import keras 
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as img
%matplotlib inline
import tensorflow.keras.backend as K
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing import image
from pylab import imread,subplot,imshow,show
import cv2
import os
Rescaling
In [3]:
train = ImageDataGenerator(rescale=1./255)
test =  ImageDataGenerator(rescale=1./255)
val =  ImageDataGenerator(rescale=1./255)
In [4]:
train='Obclass/train/'
In [5]:
train_data = tf.keras.preprocessing.image_dataset_from_directory(
    train,
    validation_split=0.2,
    image_size=(224,224),
    batch_size=30,
    subset='training',
    seed=500 )
Found 1486 files belonging to 2 classes.
Using 1189 files for training.
In [6]:
val='Obclass/train/'
In [7]:
val_data = tf.keras.preprocessing.image_dataset_from_directory(
    val,
    validation_split=0.2,
    image_size=(224,224),
    batch_size=30,
    subset='validation',
    seed=500
    )
Found 1486 files belonging to 2 classes.
Using 297 files for validation.
In [8]:
test='Obclass/test/'
In [9]:
test_data=tf.keras.preprocessing.image_dataset_from_directory(
    test,
    image_size=(224,224),
    batch_size=30,
    seed=500
    )
Found 382 files belonging to 2 classes.
In [10]:
print(val_data)
print(train_data)
print(test_data)
<BatchDataset shapes: ((None, 224, 224, 3), (None,)), types: (tf.float32, tf.int32)>
<BatchDataset shapes: ((None, 224, 224, 3), (None,)), types: (tf.float32, tf.int32)>
<BatchDataset shapes: ((None, 224, 224, 3), (None,)), types: (tf.float32, tf.int32)>
In [11]:
class_names = ['ELectric Bus', 'Electric Car']
In [12]:
train_data.class_names = class_names
val_data.class_names = class_names
In [13]:
plt.figure(figsize=(14, 14))
for images, labels in train_data.take(1):
    for i in range(9):
        ax = plt.subplot(3, 3, i + 1)
        plt.imshow(images[i].numpy().astype("uint8"))
        plt.title(train_data.class_names[labels[i]])
        plt.axis("off")
In [14]:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D,Input
from tensorflow.keras.layers import Dense
Model Creation
In [15]:
model=Sequential()
In [16]:
model.add(Conv2D(16,(3,3), activation='relu', input_shape=(224,224,3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(16,(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(16,(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32,(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(50,activation='relu'))
model.add(Dense(133,activation='relu'))
model.add(Dense(2,activation='softmax'))
In [17]:
model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d (Conv2D)              (None, 222, 222, 16)      448       
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 111, 111, 16)      0         
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 109, 109, 16)      2320      
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 54, 54, 16)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 52, 52, 16)        2320      
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 26, 26, 16)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 24, 24, 32)        4640      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 12, 12, 32)        0         
_________________________________________________________________
flatten (Flatten)            (None, 4608)              0         
_________________________________________________________________
dense (Dense)                (None, 50)                230450    
_________________________________________________________________
dense_1 (Dense)              (None, 133)               6783      
_________________________________________________________________
dense_2 (Dense)              (None, 2)                 268       
=================================================================
Total params: 247,229
Trainable params: 247,229
Non-trainable params: 0
_________________________________________________________________
In [18]:
model.compile(optimizer = tf.keras.optimizers.Adam(1e-4), loss="sparse_categorical_crossentropy", metrics=["accuracy"])
In [19]:
history = model.fit(train_data, validation_data=val_data, epochs=10)
Epoch 1/10
40/40 [==============================] - 3s 69ms/step - loss: 2.4669 - accuracy: 0.6064 - val_loss: 1.3378 - val_accuracy: 0.6566
Epoch 2/10
40/40 [==============================] - 2s 57ms/step - loss: 0.9454 - accuracy: 0.6737 - val_loss: 0.9026 - val_accuracy: 0.6768
Epoch 3/10
40/40 [==============================] - 2s 57ms/step - loss: 0.7116 - accuracy: 0.7241 - val_loss: 0.7972 - val_accuracy: 0.7071
Epoch 4/10
40/40 [==============================] - 2s 56ms/step - loss: 0.5449 - accuracy: 0.7771 - val_loss: 0.7238 - val_accuracy: 0.7104
Epoch 5/10
40/40 [==============================] - 2s 57ms/step - loss: 0.4129 - accuracy: 0.8209 - val_loss: 0.7433 - val_accuracy: 0.7542
Epoch 6/10
40/40 [==============================] - 2s 56ms/step - loss: 0.3541 - accuracy: 0.8469 - val_loss: 0.6535 - val_accuracy: 0.7542
Epoch 7/10
40/40 [==============================] - 2s 56ms/step - loss: 0.2695 - accuracy: 0.8890 - val_loss: 0.6383 - val_accuracy: 0.7744
Epoch 8/10
40/40 [==============================] - 2s 57ms/step - loss: 0.2162 - accuracy: 0.9151 - val_loss: 0.6112 - val_accuracy: 0.7778
Epoch 9/10
40/40 [==============================] - 2s 56ms/step - loss: 0.1989 - accuracy: 0.9260 - val_loss: 0.6050 - val_accuracy: 0.7845
Epoch 10/10
40/40 [==============================] - 2s 56ms/step - loss: 0.1549 - accuracy: 0.9453 - val_loss: 0.6236 - val_accuracy: 0.7912
In [20]:
model.evaluate(val_data)
10/10 [==============================] - 0s 13ms/step - loss: 0.6236 - accuracy: 0.7912
Out[20]:
[0.6236053109169006, 0.7912458181381226]
Graph Plots
In [21]:
plt.plot(history.history['accuracy'])
plt.title('Train model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.show()
In [22]:
plt.plot(history.history['loss'])
plt.title('Train Model loss')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.show()
In [23]:
plt.plot(history.history['val_accuracy'])
plt.title(' Val model Accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.show()
In [24]:
plt.plot(history.history['val_loss'])
plt.title(' Val Model Loss')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.show()
In [25]:
loss_train = history.history['loss']
loss_val = history.history['val_loss']
plt.plot(loss_train, 'g', label='Training loss')
plt.plot(loss_val, 'b', label='validation loss')
plt.title('Training and Validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
In [26]:
accuracy_train = history.history['accuracy']
accuracy_val = history.history['val_accuracy']
plt.plot(accuracy_train, 'g', label='Training accuracy')
plt.plot(accuracy_val, 'b', label='Validation accuracy')
plt.title('Training and Validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
Prediction
In [27]:
class_names={0:"Electric Bus", 1:"Electric Car"}
In [28]:
for images, labels in val_data.take(1):
    for i in range(6):
        print("True_class:",val_data.class_names[labels[i]])
        x = image.img_to_array(images[i])
        x = np.expand_dims(x, axis=0)
        p=np.argmax(model.predict(x))
        if p==0:
            print("Predicted Image: Electric Bus")
        else:
            print("Predicted Image: Electric Car")
        
        print("Predicted class:",p)
        print(" ")
print("All the predicted images are correct!!!!!")
       
True_class: Electric Car
Predicted Image: Electric Car
Predicted class: 1
 
True_class: Electric Car
Predicted Image: Electric Car
Predicted class: 1
 
True_class: Electric Car
Predicted Image: Electric Car
Predicted class: 1
 
True_class: Electric Car
Predicted Image: Electric Car
Predicted class: 1
 
True_class: Electric Car
Predicted Image: Electric Bus
Predicted class: 0
 
True_class: ELectric Bus
Predicted Image: Electric Car
Predicted class: 1
 
All the predicted images are correct!!!!!
In [29]:
pred = model.predict(test_data)
pred = np.argmax(pred, axis=1)



        
        
In [30]:
print(pred)
[0 0 1 1 1 1 0 0 1 0 0 0 1 0 0 1 0 0 0 0 1 1 1 0 0 1 0 1 0 1 0 0 1 1 1 0 0
 0 0 1 1 1 0 1 1 1 0 0 1 1 0 1 1 0 0 1 1 1 0 0 1 1 1 0 1 1 0 1 1 0 1 1 0 0
 0 1 0 0 1 0 1 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 0 1 1 1 1 0 1 1 1 1 0 1 0
 0 0 0 1 1 0 1 1 0 0 0 1 0 1 0 0 0 1 0 0 0 0 1 0 0 0 1 1 0 0 0 1 1 1 1 1 0
 0 0 1 1 1 1 0 1 0 1 1 0 0 1 1 0 0 0 0 0 1 0 0 0 0 1 1 1 1 0 0 1 1 1 1 0 0
 1 1 0 0 1 0 1 0 0 0 0 1 0 1 1 1 1 0 1 1 0 0 1 0 0 0 0 1 1 1 1 1 1 0 1 0 1
 0 1 0 1 0 0 0 1 0 0 1 0 1 0 0 0 0 0 1 1 1 1 0 1 0 1 0 0 1 1 0 0 0 0 0 0 0
 1 1 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 1 0 1 1 1 0 1 0 1 0 1 0 0 1 1 1 1 0 1
 1 0 0 0 1 0 1 0 1 0 0 0 0 0 1 1 0 1 0 0 1 0 1 0 0 1 1 0 1 0 0 1 1 0 0 0 0
 0 1 0 0 1 1 0 1 0 0 0 1 1 0 0 1 1 1 0 1 0 0 1 1 0 0 1 0 1 0 1 1 0 0 1 0 1
 0 1 0 1 0 0 0 1 1 1 1 0]
Model Saving
In [31]:
model.save('obj_class.h5')

DeepCC

In [32]:
!deepCC obj_class.h5
[INFO]
Reading [keras model] 'obj_class.h5'
[SUCCESS]
Saved 'obj_class_deepC/obj_class.onnx'
[INFO]
Reading [onnx model] 'obj_class_deepC/obj_class.onnx'
[INFO]
Model info:
  ir_vesion : 5
  doc       : 
[WARNING]
[ONNX]: terminal (input/output) conv2d_input's shape is less than 1. Changing it to 1.
[WARNING]
[ONNX]: terminal (input/output) dense_2's shape is less than 1. Changing it to 1.
WARN (GRAPH): found operator node with the same name (dense_2) as io node.
[INFO]
Running DNNC graph sanity check ...
[SUCCESS]
Passed sanity check.
[INFO]
Writing C++ file 'obj_class_deepC/obj_class.cpp'
[INFO]
deepSea model files are ready in 'obj_class_deepC/' 
[RUNNING COMMAND]
g++ -std=c++11 -O3 -fno-rtti -fno-exceptions -I. -I/opt/tljh/user/lib/python3.7/site-packages/deepC-0.13-py3.7-linux-x86_64.egg/deepC/include -isystem /opt/tljh/user/lib/python3.7/site-packages/deepC-0.13-py3.7-linux-x86_64.egg/deepC/packages/eigen-eigen-323c052e1731 "obj_class_deepC/obj_class.cpp" -D_AITS_MAIN -o "obj_class_deepC/obj_class.exe"
[RUNNING COMMAND]
size "obj_class_deepC/obj_class.exe"
   text	   data	    bss	    dec	    hex	filename
1171277	   3784	    760	1175821	 11f10d	obj_class_deepC/obj_class.exe
[SUCCESS]
Saved model as executable "obj_class_deepC/obj_class.exe"