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

Car - Bus Classification

Credit: AITS Cainvas Community

Photo by Ahmed Maghrabi on Dribbble

In [1]:
!wget "https://cainvas-static.s3.amazonaws.com/media/user_data/cainvas-admin/car_bus.zip"
--2021-09-10 18:22:43--  https://cainvas-static.s3.amazonaws.com/media/user_data/cainvas-admin/car_bus.zip
Resolving cainvas-static.s3.amazonaws.com (cainvas-static.s3.amazonaws.com)... 52.219.62.0
Connecting to cainvas-static.s3.amazonaws.com (cainvas-static.s3.amazonaws.com)|52.219.62.0|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 79013537 (75M) [application/x-zip-compressed]
Saving to: ‘car_bus.zip’

car_bus.zip         100%[===================>]  75.35M  62.3MB/s    in 1.2s    

2021-09-10 18:22:44 (62.3 MB/s) - ‘car_bus.zip’ saved [79013537/79013537]

In [2]:
!unzip -qo "car_bus.zip"

Importing Libraries

In [3]:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPool2D
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Dropout
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
from matplotlib.image import imread

Image Preprocessing

In [4]:
 
train_datagen = ImageDataGenerator(rescale = 1/255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1/255)

training_set = train_datagen.flow_from_directory('Training_set/Training_set', target_size = (200, 200), batch_size=16, class_mode='binary')
test_set = test_datagen.flow_from_directory('test/test', target_size=(200, 200), batch_size = 16, class_mode = 'binary')
Found 1486 images belonging to 2 classes.
Found 382 images belonging to 2 classes.

Creating model and Layers

In [5]:
model = Sequential()


model.add(Conv2D(64, (3, 3), input_shape=(200, 200, 3), activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Conv2D(32, (3, 3), activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Conv2D(16, (3, 3), activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Conv2D(10, (3, 3), activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))


model.add(Flatten())
model.add(Dense(units = 64, activation = 'relu'))
model.add(Dropout(0.4))
model.add(Dense(units=1, activation = 'sigmoid'))

Compiling model and Train model

In [6]:
model.compile(optimizer = 'adam',loss = 'binary_crossentropy', metrics = ['accuracy'])

history = model.fit_generator(training_set, epochs = 20, validation_data=test_set)
WARNING:tensorflow:From <ipython-input-6-b0c4510a9c89>:3: Model.fit_generator (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.
Instructions for updating:
Please use Model.fit, which supports generators.
Epoch 1/20
 1/93 [..............................] - ETA: 0s - loss: 0.6929 - accuracy: 0.4375WARNING:tensorflow:Callbacks method `on_train_batch_end` is slow compared to the batch time (batch time: 0.0074s vs `on_train_batch_end` time: 0.0128s). Check your callbacks.
93/93 [==============================] - 13s 141ms/step - loss: 0.6076 - accuracy: 0.6608 - val_loss: 0.4773 - val_accuracy: 0.7984
Epoch 2/20
93/93 [==============================] - 13s 139ms/step - loss: 0.4664 - accuracy: 0.8048 - val_loss: 0.4012 - val_accuracy: 0.8115
Epoch 3/20
93/93 [==============================] - 13s 139ms/step - loss: 0.4130 - accuracy: 0.8257 - val_loss: 0.3832 - val_accuracy: 0.8246
Epoch 4/20
93/93 [==============================] - 13s 139ms/step - loss: 0.3680 - accuracy: 0.8398 - val_loss: 0.2919 - val_accuracy: 0.8927
Epoch 5/20
93/93 [==============================] - 13s 138ms/step - loss: 0.3393 - accuracy: 0.8546 - val_loss: 0.3433 - val_accuracy: 0.8665
Epoch 6/20
93/93 [==============================] - 13s 139ms/step - loss: 0.3458 - accuracy: 0.8600 - val_loss: 0.2838 - val_accuracy: 0.8770
Epoch 7/20
93/93 [==============================] - 13s 139ms/step - loss: 0.3096 - accuracy: 0.8742 - val_loss: 0.2552 - val_accuracy: 0.9031
Epoch 8/20
93/93 [==============================] - 13s 139ms/step - loss: 0.2829 - accuracy: 0.8943 - val_loss: 0.2502 - val_accuracy: 0.9058
Epoch 9/20
93/93 [==============================] - 13s 138ms/step - loss: 0.2796 - accuracy: 0.8977 - val_loss: 0.2564 - val_accuracy: 0.8953
Epoch 10/20
93/93 [==============================] - 13s 140ms/step - loss: 0.2400 - accuracy: 0.9065 - val_loss: 0.2571 - val_accuracy: 0.8979
Epoch 11/20
93/93 [==============================] - 13s 138ms/step - loss: 0.2673 - accuracy: 0.8930 - val_loss: 0.2541 - val_accuracy: 0.8874
Epoch 12/20
93/93 [==============================] - 13s 139ms/step - loss: 0.2349 - accuracy: 0.9065 - val_loss: 0.2348 - val_accuracy: 0.9084
Epoch 13/20
93/93 [==============================] - 13s 138ms/step - loss: 0.2114 - accuracy: 0.9152 - val_loss: 0.2787 - val_accuracy: 0.8874
Epoch 14/20
93/93 [==============================] - 13s 139ms/step - loss: 0.1944 - accuracy: 0.9219 - val_loss: 0.1625 - val_accuracy: 0.9372
Epoch 15/20
93/93 [==============================] - 13s 138ms/step - loss: 0.1925 - accuracy: 0.9199 - val_loss: 0.1925 - val_accuracy: 0.9293
Epoch 16/20
93/93 [==============================] - 13s 139ms/step - loss: 0.1923 - accuracy: 0.9266 - val_loss: 0.1983 - val_accuracy: 0.9241
Epoch 17/20
93/93 [==============================] - 13s 139ms/step - loss: 0.1671 - accuracy: 0.9347 - val_loss: 0.1820 - val_accuracy: 0.9215
Epoch 18/20
93/93 [==============================] - 13s 139ms/step - loss: 0.1812 - accuracy: 0.9347 - val_loss: 0.2224 - val_accuracy: 0.9188
Epoch 19/20
93/93 [==============================] - 13s 138ms/step - loss: 0.1608 - accuracy: 0.9361 - val_loss: 0.1516 - val_accuracy: 0.9476
Epoch 20/20
93/93 [==============================] - 13s 138ms/step - loss: 0.1485 - accuracy: 0.9462 - val_loss: 0.2274 - val_accuracy: 0.9058

Our model Summary

In [7]:
model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d (Conv2D)              (None, 198, 198, 64)      1792      
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 99, 99, 64)        0         
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 97, 97, 32)        18464     
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 48, 48, 32)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 46, 46, 16)        4624      
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 23, 23, 16)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 21, 21, 10)        1450      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 10, 10, 10)        0         
_________________________________________________________________
flatten (Flatten)            (None, 1000)              0         
_________________________________________________________________
dense (Dense)                (None, 64)                64064     
_________________________________________________________________
dropout (Dropout)            (None, 64)                0         
_________________________________________________________________
dense_1 (Dense)              (None, 1)                 65        
=================================================================
Total params: 90,459
Trainable params: 90,459
Non-trainable params: 0
_________________________________________________________________

Model Evaluation

In [8]:
model.evaluate(test_set)
24/24 [==============================] - 1s 25ms/step - loss: 0.2274 - accuracy: 0.9058
Out[8]:
[0.2273520827293396, 0.9057591557502747]
In [9]:
from matplotlib.image import imread

for i in range(9):
    plt.figure(i)
    plt.subplot(330+1+i)
    img = imread('test/test/electric car/electric__image-10'+str(i)+'.jpeg')
    plt.imshow(img)
print(img.shape)
(315, 474, 3)
In [10]:
CATEGORIES = ["electric car", "electric bus"]
import cv2
image_array = cv2.imread('training_set/Training_set/electric bus/821c1f91.jpg', cv2.IMREAD_GRAYSCALE)
plt.imshow(image_array, cmap = 'gray')
plt.show()
In [11]:
new_array = cv2.resize(image_array, (90, 90))
plt.imshow(new_array, cmap='gray')
plt.show()

Prediction

In [12]:
import numpy as np
CATEGORIES = ["electric car", "electric bus"]
def prepare(num=1):
    batch = None
    for i in range(num):
        batch = next(test_set)
    img = batch[0]
    label = batch[1]
    return img[0], label

#model = tf.keras.models.load_model('car_bus_classification.m5')

test_img, _ = prepare(5)
prediction = model.predict(np.expand_dims(test_img, axis=0))
print(prediction)
print(CATEGORIES[int(prediction[0][0])])
[[0.00134974]]
electric car

Accuracy Graph

In [13]:
accuracy_train = history.history['accuracy']
accuracy_val = history.history['val_accuracy']
plt.plot(accuracy_train, 'r--', label = 'training accuracy', linewidth = 1)
plt.plot(accuracy_val, 'b--', label = 'validation accuracy', linewidth = 1)
plt.title('training accuracy and validation accuracy')
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.legend()
plt.grid()
plt.show()

Loss Graph

In [14]:
loss_train = history.history['loss']
loss_val = history.history['val_loss']
plt.plot(loss_train, 'r--', label = 'training loss')
plt.plot(loss_val, 'b--', label = 'validation loss')
plt.title('training loss and validation loss')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.legend()
plt.grid()
plt.show()
In [18]:
model.save('car_bus_classification.h5')
In [19]:
!deepCC car_bus_classification.h5
[INFO]
Reading [keras model] 'car_bus_classification.h5'
[SUCCESS]
Saved 'car_bus_classification_deepC/car_bus_classification.onnx'
[INFO]
Reading [onnx model] 'car_bus_classification_deepC/car_bus_classification.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_1's shape is less than 1. Changing it to 1.
WARN (GRAPH): found operator node with the same name (dense_1) as io node.
[INFO]
Running DNNC graph sanity check ...
[SUCCESS]
Passed sanity check.
[INFO]
Writing C++ file 'car_bus_classification_deepC/car_bus_classification.cpp'
[INFO]
deepSea model files are ready in 'car_bus_classification_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 "car_bus_classification_deepC/car_bus_classification.cpp" -D_AITS_MAIN -o "car_bus_classification_deepC/car_bus_classification.exe"
[RUNNING COMMAND]
size "car_bus_classification_deepC/car_bus_classification.exe"
   text	   data	    bss	    dec	    hex	filename
 539131	   3768	    760	 543659	  84bab	car_bus_classification_deepC/car_bus_classification.exe
[SUCCESS]
Saved model as executable "car_bus_classification_deepC/car_bus_classification.exe"