You must know what is Keras
Problem:
We have to make such an ImageClassifier that after seeing the image, tell it whether it is a cat or a dog (In this particular problem)
Basically we will first train our CNN models with a lot of images of cats and dogs.
Why CNN: As we have seen in CNN tutorial,CNN reads a very large image in a simple manner. CNN most commonly used to analyze visual imagery and are frequently working behind the scenes in image classification.
For Official documentation of Keras (Click Here) ,and for tensorflow (click here).
CNN CAT and DOG Implementation
# Part 1 - Building the CNN # Importing the Keras libraries and packages from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense |
---|
Note
- In this part of code, we have imported Keras and its libraries/layers.
- As the version of TensorFlow changes, the way the importing of Keras and keras models changes, so check out official documentation (Links given above). (here tensorflow version 1 is used)
# Initialising the CNN classifier = Sequential() |
---|
Note
- The Sequential model API (Application Programming Interface) is a way of creating deep learning models where an instance of the Sequential class is created and model layers are created and added to it.
- Basically here it works as a classifier.
# Step 1 - Convolution classifier.add(Conv2D(16, (3, 3), input_shape = (64, 64, 3), activation = 'relu')) |
---|
Note
- We have to come up with a lot of layers in CNN classification, here we have added the convolution layer with the Relu activation function (Rectified Linear Unit).
- Input_shape represent here the RGB format of images. (3, 3) represent the size of kernel/ filter.
# Step 2 - Pooling classifier.add(MaxPooling2D(pool_size = (2, 2))) |
---|
Note
- The convolved layer/ feature map that we get after passing through the convolution layer and the relu function.
- The convolved layer / feature map is then passed to the pooling layer.
- Pooling size: Integer, size of the max pooling windows.
# Adding a second convolutional layer classifier.add(Conv2D(64, (3, 3), activation = 'relu')) classifier.add(MaxPooling2D(pool_size = (2, 2))) |
---|
Note
- We pass the images to the layers more than once, in CNN classification for better feature extraction.
- So we have used the convolution layer and the pooling layer again here.
# Step 3 - Flattening classifier.add(Flatten()) |
---|
Note
After max pooling, we create a flatten layer of the matrix we get form max pooling.flatten layer is basically works as input layer for CNN neural network.
# Step 4 - Full connection classifier.add(Dense(units = 128, activation = 'relu')) classifier.add(Dense(units = 1, activation = 'sigmoid')) |
---|
Note:
- Activations can either be used through an Activation layer, or through the activation argument.
- Here we used activation layer to perform activation function.
# Compiling the CNN classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) |
---|
Note
- A metric is a function that is used to judge the performance of your model.
- The optimizers are used for improving speed and performance for training a specific model.
# Part 2 - Training of the model Defining Train and Test Data to train the model from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale = 1./255) test_datagen = ImageDataGenerator(rescale = 1./255) training_set = test_datagen.flow_from_directory('D:\\AI\\1AI_training\\module 7 Convolutional Neural Networks (CNN)\\Cat_Dog_CNN_Classifier_master\\dataset\\training_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary') test_set = test_datagen.flow_from_directory( 'D:\\AI\\1AI_training\\module 7 Convolutional Neural Networks (CNN)\\Cat_Dog_CNN_Classifier_master\\dataset\\test_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary') |
---|
Output

Note
- Look at the text highlighted with purple color, this is just the path where I saved the data of cat and dog images in my computer.
- We just loaded the data here. In the data we have a lot of images of catsand Dogs. (To extract their features )
Here we have two types of data sets. Training Data Set (8000 images )and Testing Data Set ( 2000 images).
If seen, the testing datasets would also be like a training datasets. Because our model is also learning in testing.
# Training the model (It will take time) classifier.fit_generator(training_set, steps_per_epoch = 8000, epochs = 2 , validation_data = test_set, validation_steps = 2000) #Saving trained model classifier.save('my_model_catdog.h5') |
---|
Output
4
#Saving the model from keras.models import load_model classifier=load_model('my_model_catdog.h5') |
---|
Note
- In this part, we have trained our model and saved the model.
- epochs = 2 means two circles. In simple language, we have seen or read an image twice.
As you can see, our datasets is very large and the model takes a lot of time to training.
By saving the model once, there will be no need to train the model again and again for prediction. And we can do prediction by just loading the model.(The second shell of code).
This means that you only have to run the training model shell once.
After that you can do prediction by running the shell of load model.