In this article, we will use Convolutional Neural Network to solve a Supervised Image
Classification problem of recognizing the flower types – rose, chamomile, dandelion, sunflower, & tulip. Understanding the concept of a Convolutional Neural Network refers to this.
Once, understand the concept of CNN we can start with the project.
Steps to be followed
The steps followed in this article are listed here :
- Importing modules
- Importing Dataset
- Image Data Generator
- Model Development
- Model Evaluation and Prediction
Importing modules
- Pandas – This library helps to load the data frame in a 2D array format.
- Numpy – Numpy arrays are very fast and can perform large computations.
- Matplotlib – This library is used to draw visualizations.
- Sklearn – This module contains multiple libraries having pre-implemented functions to perform tasks from data preprocessing to model development and evaluation.
- OpenCV – This library focuses on image processing and handling.
- Tensorflow – It has a range of functions to achieve complex functionalities with single lines of code.
Python3
import numpy as np import pandas as pd import cv2 import matplotlib.pyplot as plt from PIL import Image from tensorflow.keras import layers from tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, MaxPooling2D from tensorflow.keras.layers import Activation, Dropout, Flatten, Dense from tensorflow.keras.optimizers import Adam import tensorflow as tf import os |
Importing Dataset and Preprocessing
You can download the dataset from the link.
Once download the data, image resize is needed to be done. To specify the size of the image use below code.
Python3
base_dir = '/flowers/' img_size = 224 batch = 64 |
Image Data Generator
For image data generator, follow the code given below.
Python3
# Create a data augmentor train_datagen = ImageDataGenerator(rescale = 1. / 255 , shear_range = 0.2 , zoom_range = 0.2 , horizontal_flip = True , validation_split = 0.2 ) test_datagen = ImageDataGenerator(rescale = 1. / 255 , validation_split = 0.2 ) # Create datasets train_datagen = train_datagen.flow_from_directory(base_dir, target_size = ( img_size, img_size), subset = 'training' , batch_size = batch) test_datagen = test_datagen.flow_from_directory(base_dir, target_size = ( img_size, img_size), subset = 'validation' , batch_size = batch) |
Output :
Found 3121 images belonging to 5 classes. Found 776 images belonging to 5 classes.
Model Development
From here we will use the we creating CNN model with the help of tensorflow library as it contains all the functionalities that one may need to define the architecture of a Convolutional Neural Network and train it on the data.
Python3
# # modelling starts using a CNN. model = Sequential() model.add(Conv2D(filters = 64 , kernel_size = ( 5 , 5 ), padding = 'same' , activation = 'relu' , input_shape = ( 224 , 224 , 3 ))) model.add(MaxPooling2D(pool_size = ( 2 , 2 ))) model.add(Conv2D(filters = 64 , kernel_size = ( 3 , 3 ), padding = 'same' , activation = 'relu' )) model.add(MaxPooling2D(pool_size = ( 2 , 2 ), strides = ( 2 , 2 ))) model.add(Conv2D(filters = 64 , kernel_size = ( 3 , 3 ), padding = 'same' , activation = 'relu' )) model.add(MaxPooling2D(pool_size = ( 2 , 2 ), strides = ( 2 , 2 ))) model.add(Conv2D(filters = 64 , kernel_size = ( 3 , 3 ), padding = 'same' , activation = 'relu' )) model.add(MaxPooling2D(pool_size = ( 2 , 2 ), strides = ( 2 , 2 ))) model.add(Flatten()) model.add(Dense( 512 )) model.add(Activation( 'relu' )) model.add(Dense( 5 , activation = "softmax" )) |
Summary of the model
Python3
model.summary() |
Output :
Python3
keras.utils.plot_model( model, show_shapes = True , show_dtype = True , show_layer_activations = True ) |
Output:
Compiling
Python3
model. compile (optimizer = tf.keras.optimizers.Adam(), loss = 'categorical_crossentropy' , metrics = [ 'accuracy' ]) |
Fitting
Model Fitting will take some time.
Python3
epochs = 30 model.fit(train_datagen,epochs = epochs,validation_data = test_datagen) |
Output:
Saving and Loading model
For more information regarding saving and loading models refer this.
Python3
from tensorflow.keras.models import load_model model.save( 'Model.h5' ) # load model savedModel = load_model( 'Model.h5' ) |
Once you saved the model, you can use it anytime without training again and again.
Model Evaluation and Prediction
Evaluation includes the hyperparameter tuning if the model is not giving good results. You can also play with different parameters for better predictions.
Python3
train_datagen.class_indices |
Output :
{'daisy': 0, 'dandelion': 1, 'rose': 2, 'sunflower': 3, 'tulip': 4}
Python3
from keras.preprocessing import image #Creating list for mapping list_ = [ 'Daisy' , 'Danelion' , 'Rose' , 'sunflower' , 'tulip' ] #Input image test_image = image.load_img( 'img.jpg' ,target_size = ( 224 , 224 )) #For show image plt.imshow(test_image) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image,axis = 0 ) # Result array result = savedModel.predict(test_image) print (result) #Mapping result array with the main name list i = 0 for i in range ( len (result[ 0 ])): if (result[ 0 ][i] = = 1 ): print (list_[i]) break |
Output:
Python3
#Input image test_image = image.load_img( 'img2.jpg' ,target_size = ( 224 , 224 )) #For show image plt.imshow(test_image) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image,axis = 0 ) # Result array result = savedModel.predict(test_image) print (result) #Mapping result array with the main name list i = 0 for i in range ( len (result[ 0 ])): if (result[ 0 ][i] = = 1 ): print (list_[i]) break |
Output:
Conclusion
We can improve the results by using Transfer Learning like Resnet50.