FIFA-2022 Career Guide Free Tutorials Go to Your University Placement Preparation 
0 like 0 dislike
2.5k views
in Artificial Intelligence(AI) & Machine Learning by Goeduhub's Expert (3.1k points)
Cat Dog classification using CNN

2 Answers

0 like 0 dislike
by Goeduhub's Expert (3.1k points)
edited by
 
Best answer

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

  1. In this part of code, we have imported Keras and its libraries/layers.
  2. 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

  1. 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.  
  2. Basically here it works as a classifier.

# Step 1 - Convolution

classifier.add(Conv2D(16, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))

Note

  1. 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).
  2. 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

  1. The convolved layer/ feature map  that we get after passing through the convolution layer and the relu function.
  2. The convolved layer / feature map is then passed to the pooling layer.
  3. 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

  1. We pass the images to the layers more than once, in CNN classification for better feature extraction.
  2. 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:

  1.  Activations can either be used through an Activation layer, or through the activation argument.
  2. Here we used activation layer to perform activation function.

 # Compiling the CNN

classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

 Note

  1. A metric is a function that is used to judge the performance of your model.  
  2. 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

  1. 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. 
  2. We just loaded the data here. In the data we have a lot of images of catsand Dogs. (To extract their features )
  3. Here we have two types of data sets. Training Data Set (8000 images )and Testing Data Set ( 2000 images).

  4. 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

  1. In this part, we have trained our model and saved the model.
  2. epochs = 2 means two circles. In simple language, we have seen or read an image twice.
  3. As you can see, our datasets is very large and the model takes a lot of time to training.

  4. 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). 

  5. 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. 

0 like 0 dislike
by Goeduhub's Expert (3.1k points)
edited by

# Part 3 - Making new predictions

import numpy as np

from keras.preprocessing import image

test_image = image.load_img('D:\\AI\\1AI_training\\module 7 

Convolutional Neural Networks (CNN)\\Cat_Dog_CNN_Classifier_master\

\dataset\\single_prediction\\cat_and_dog.jpg',target_size = (300, 300)) 

import matplotlib.pyplot as plt

from matplotlib.pyplot import imshow

%matplotlib inline

plt.imshow(test_image)

Output

Note

  1. In this code we are taking a test image. And printed it with the help of MatplotLib.
  2. We have shown the image here so that we can see what is in the image. And then we will get this image predicated from the model.

#Cat and dog classification

import numpy as np

from keras.preprocessing import image

test_image = image.load_img('D:\\AI\\1AI_training\\module 7 

Convolutional Neural Networks (CNN)\\Cat_Dog_CNN_Classifier_master\\dataset\\single_prediction

\\cat_and_dog.jpg', target_size = (64, 64))

test_image = image.img_to_array(test_image)

test_image = np.expand_dims(test_image, axis = 0)

result = classifier.predict(test_image)

training_set.class_indices

if result[0][0] == 1:

    prediction = 'dog'

else:

    prediction = 'cat'

prediction

 Output

Note

  1. In this code, we have done preprocessing of  new image. Which is necessary,basically  bring your target image to the size of the training image is preprocessing of image.
  2. training_set.class_indices: either 1 (Dog ) or 0 (Cat).
  3. You can see the final output is dog because the dog in our image was dominating, so its feature is recognized by model is more than that of CAT.

Learn & Improve In-Demand Data Skills Online in this Summer With  These High Quality Courses[Recommended by GOEDUHUB]:-

Best Data Science Online Courses[Lists] on:-

Claim your 10 Days FREE Trial for Pluralsight.

Best Data Science Courses on Datacamp
Best Data Science Courses on Coursera
Best Data Science Courses on Udemy
Best Data Science Courses on Pluralsight
Best Data Science Courses & Microdegrees on Udacity
Best Artificial Intelligence[AI] Courses on Coursera
Best Machine Learning[ML] Courses on Coursera
Best Python Programming Courses on Coursera
Best Artificial Intelligence[AI] Courses on Udemy
Best Python Programming Courses on Udemy

Related questions

0 like 0 dislike
1 answer 327 views
0 like 0 dislike
1 answer 609 views
asked Jan 31, 2020 in Python Programming by Nisha Goeduhub's Expert (3.1k points)
0 like 0 dislike
1 answer 264 views

 Important Lists:

Important Lists, Exams & Cutoffs Exams after Graduation PSUs

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy ||  Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 

 

Free Online Directory

...