Image Classification Using SVM.ipynb

Collins Akala

Data Visualizer
Data Analyst
Jupyter Notebook
Python
Visual Studio Code
Pane width
Use a value between 19% and 30%

Files

Image Classification Using SVM.ipynb
README.md

Breadcrumbs

/

Latest commit

File metadata and controls

600 lines (600 loc) · 88.3 KB

SVM IN CNN FOR IMAGE CLASSIFICATION

In [1]:
import tensorflow as tf

Initiating a command to use 50% of the GPU share memory

In [2]:
from tensorflow.compat.v1 import ConfigProto from tensorflow.compat.v1 import InteractiveSession config = ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.5 config.gpu_options.allow_growth = True session = InteractiveSession(config=config)

Now we upload image data generator

In [3]:
from tensorflow.keras.preprocessing.image import ImageDataGenerator

Use the ImageDataGenerator for data augumentation

The reason behind the augumentation of train data set is to add noise (systemaically or randomly alter the image) to increase the size of the data to make it robust enough to cover any aspect or possible ways the data could be generated. This will as well help our model to be trained enough to produce an outcome that incoporate different data from different possible ways
In [4]:
# Data Preprocessing # Preprocessing the Training set train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True)
In [5]:
training_set = train_datagen.flow_from_directory('Dataset/train', target_size = (64, 64), batch_size = 32, class_mode = 'binary') # Preparing the Test data test_datagen = ImageDataGenerator(rescale = 1./255) test_set = test_datagen.flow_from_directory('Dataset/test', target_size = (64, 64), batch_size = 32, class_mode = 'binary') Found 20000 images belonging to 2 classes. Found 5000 images belonging to 2 classes.

Import two layer to create a plan neural network

In [6]:
from tensorflow.keras.layers import Conv2D # for convolution operations from tensorflow.keras.layers import Dense # to add the node with respect to header list
In [7]:
from tensorflow.keras.regularizers import l2
In [8]:
# Initializing the CNN cnn = tf.keras.models.Sequential() # Step 1 - Convolution cnn.add(tf.keras.layers.Conv2D(filters=32,padding="same",kernel_size=3, activation='relu', strides=2, input_shape=[64, 64, 3])) # Step 2 - Pooling cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2)) # Adding a second convolutional layer cnn.add(tf.keras.layers.Conv2D(filters=32,padding='same',kernel_size=3, activation='relu')) cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2)) # Step 3 - Flattening cnn.add(tf.keras.layers.Flatten()) # Step 4 - Full Connection cnn.add(tf.keras.layers.Dense(units=128, activation='relu')) # Step 5 - Output Layer #cnn.add(tf.keras.layers.Dense(units=1, activation='sigmoid')) ## For Binary Classification cnn.add(Dense(1, kernel_regularizer=tf.keras.regularizers.l2(0.01),activation ='linear')) # to make it as linear SVM
In [9]:
## for mulitclassification ## cnn.add(Dense(4, kernel_regularizer=tf.keras.regularizers.l2(0.01),activation ='softmax')) ## cnn.compile(optimizer = 'adam', loss = 'squared_hinge', metrics = ['accuracy'])
In [10]:
cnn.summary() Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 32, 32, 32) 896 max_pooling2d (MaxPooling2D (None, 16, 16, 32) 0 ) conv2d_1 (Conv2D) (None, 16, 16, 32) 9248 max_pooling2d_1 (MaxPooling (None, 8, 8, 32) 0 2D) flatten (Flatten) (None, 2048) 0 dense (Dense) (None, 128) 262272 dense_1 (Dense) (None, 1) 129 ================================================================= Total params: 272,545 Trainable params: 272,545 Non-trainable params: 0 _________________________________________________________________
In [11]:
# Part 3 - Training the CNN # Compiling the CNN cnn.compile(optimizer = 'adam', loss = 'hinge', metrics = ['accuracy']) # using the loss function as hinge is going to be consider as SVM # Training the CNN on the Training set and evaluating it on the Test set r=cnn.fit(x = training_set, validation_data = test_set, epochs = 15) # using the loss function as hinge and regularizer made our final layer an SVM layer Epoch 1/15 625/625 [==============================] - 132s 208ms/step - loss: 0.7768 - accuracy: 0.6371 - val_loss: 0.6610 - val_accuracy: 0.7264 Epoch 2/15 625/625 [==============================] - 119s 191ms/step - loss: 0.6312 - accuracy: 0.7052 - val_loss: 0.6339 - val_accuracy: 0.7514 Epoch 3/15 625/625 [==============================] - 119s 191ms/step - loss: 0.5744 - accuracy: 0.7327 - val_loss: 0.5974 - val_accuracy: 0.7650 Epoch 4/15 625/625 [==============================] - 119s 191ms/step - loss: 0.5485 - accuracy: 0.7435 - val_loss: 0.5178 - val_accuracy: 0.7442 Epoch 5/15 625/625 [==============================] - 119s 191ms/step - loss: 0.5201 - accuracy: 0.7591 - val_loss: 0.5324 - val_accuracy: 0.7858 Epoch 6/15 625/625 [==============================] - 116s 185ms/step - loss: 0.5041 - accuracy: 0.7682 - val_loss: 0.4777 - val_accuracy: 0.7964 Epoch 7/15 625/625 [==============================] - 119s 190ms/step - loss: 0.4938 - accuracy: 0.7706 - val_loss: 0.4644 - val_accuracy: 0.7914 Epoch 8/15 625/625 [==============================] - 129s 206ms/step - loss: 0.4767 - accuracy: 0.7807 - val_loss: 0.4780 - val_accuracy: 0.8040 Epoch 9/15 625/625 [==============================] - 125s 200ms/step - loss: 0.4624 - accuracy: 0.7860 - val_loss: 0.4831 - val_accuracy: 0.7994 Epoch 10/15 625/625 [==============================] - 128s 204ms/step - loss: 0.4560 - accuracy: 0.7924 - val_loss: 0.5152 - val_accuracy: 0.8038 Epoch 11/15 625/625 [==============================] - 142s 227ms/step - loss: 0.4414 - accuracy: 0.7965 - val_loss: 0.4553 - val_accuracy: 0.7814 Epoch 12/15 625/625 [==============================] - 138s 221ms/step - loss: 0.4358 - accuracy: 0.8004 - val_loss: 0.4450 - val_accuracy: 0.8080 Epoch 13/15 625/625 [==============================] - 155s 248ms/step - loss: 0.4266 - accuracy: 0.8048 - val_loss: 0.4247 - val_accuracy: 0.8126 Epoch 14/15 625/625 [==============================] - 156s 249ms/step - loss: 0.4210 - accuracy: 0.8109 - val_loss: 0.4131 - val_accuracy: 0.8256 Epoch 15/15 625/625 [==============================] - 184s 294ms/step - loss: 0.4132 - accuracy: 0.8110 - val_loss: 0.4239 - val_accuracy: 0.8236
In [12]:
# plot the loss import matplotlib.pyplot as plt plt.plot(r.history['loss'], label='train loss') plt.plot(r.history['val_loss'], label='val loss') plt.legend() plt.show() plt.savefig('LossVal_loss') # plot the accuracy plt.plot(r.history['accuracy'], label='train acc') plt.plot(r.history['val_accuracy'], label='val acc') plt.legend() plt.show() plt.savefig('AccVal_acc') <Figure size 640x480 with 0 Axes>
In [13]:
# save it as a h5 file from tensorflow.keras.models import load_model cnn.save('model_rcat_dog.h5')
In [14]:
from tensorflow.keras.models import load_model # load model model = load_model('model_rcat_dog.h5')
In [15]:
model.summary() Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 32, 32, 32) 896 max_pooling2d (MaxPooling2D (None, 16, 16, 32) 0 ) conv2d_1 (Conv2D) (None, 16, 16, 32) 9248 max_pooling2d_1 (MaxPooling (None, 8, 8, 32) 0 2D) flatten (Flatten) (None, 2048) 0 dense (Dense) (None, 128) 262272 dense_1 (Dense) (None, 1) 129 ================================================================= Total params: 272,545 Trainable params: 272,545 Non-trainable params: 0 _________________________________________________________________
In [17]:
# Part 4 - Making a single prediction import numpy as np from tensorflow.keras.preprocessing import image test_image = image.load_img('Dataset/test/Dogs/dog.30.jpg', target_size = (64,64)) test_image = image.img_to_array(test_image) test_image=test_image/255 test_image = np.expand_dims(test_image, axis = 0) result = cnn.predict(test_image) 1/1 [==============================] - 0s 280ms/step
In [18]:
result
Out[18]:
array([[1.1500416]], dtype=float32)
In [19]:
if result[0]<0: print("The image classified is cat") else: print("The image classified is dog") The image classified is dog

Also we need to test for a cat

In [20]:
import numpy as np from tensorflow.keras.preprocessing import image test_image = image.load_img('Dataset/test/Cats/cat.30.jpg', target_size = (64,64)) test_image = image.img_to_array(test_image) test_image=test_image/255 test_image = np.expand_dims(test_image, axis = 0) result = cnn.predict(test_image)
Partner With Collins
View Services

More Projects by Collins