<jupyter_start><jupyter_text>In the below notebook we are trying to classify the image of dogs and cats. In below we are trying to find whether a image contains a picture of dog or a cat.To classify this we are going to use CNN and tesorflow.  * Tensorflow: 2<  * Python :3<    **Steps:**      *           Importing Libraries<jupyter_code>import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator
tf.__version__<jupyter_output><empty_output><jupyter_text>Data Preprocessing  Preprocessing the training set<jupyter_code>train_datagen = ImageDataGenerator(
        rescale=1./255,     ## Feature scalling
        shear_range=0.2,    ## Creating Modified versions of image
        zoom_range=0.2,     ## Zooming image 
        horizontal_flip=True) ## Rotating image
training_set = train_datagen.flow_from_directory(
        'dataset/training_set',  ##Path leading to the training set
        target_size=(64, 64),  ## final size of the images when they fed into cnn 
        batch_size=32,  ## Size of the batches
        class_mode='binary')  ## Binary of categorical<jupyter_output>Found 8000 images belonging to 2 classes.<jupyter_text>Preprocessing the test set<jupyter_code>test_datagen = ImageDataGenerator(rescale=1./255)  ## Scalling the pixels
test_set = test_datagen.flow_from_directory(
        'dataset/test_set',  ## Path leads to test set
        target_size=(64, 64),  ## Final size of the image it will be same as the training images
        batch_size=32,           ## Same with the training images
        class_mode='binary')     ## Same with the training images<jupyter_output>Found 2000 images belonging to 2 classes.<jupyter_text>Building The CNN<jupyter_code># create an object of sequential class
cnn = tf.keras.models.Sequential()<jupyter_output><empty_output><jupyter_text>Step 1 : Convolution<jupyter_code>cnn.add(tf.keras.layers.Conv2D(filters=32,kernel_size=3,activation="relu",input_shape=[64,64,3]))
###filters - no. of filters , kernal_size = feature detector/matrix size(3x3) , activation = relu(rectifier), input_shape = size of images as above<jupyter_output><empty_output><jupyter_text>Step 2 : Pooling<jupyter_code>cnn.add(tf.keras.layers.MaxPool2D(pool_size=(2,2),
                                  strides=2))
## pool_size : size of square (2x2)
## strides : no of pixels the square shift
## padding : at the end of cell<jupyter_output><empty_output><jupyter_text>Adding a second convolution layer<jupyter_code>cnn.add(tf.keras.layers.Conv2D(filters=32,kernel_size=3,activation="relu"))
cnn.add(tf.keras.layers.MaxPool2D(pool_size=(2,2),
                                  strides=2))<jupyter_output><empty_output><jupyter_text>Step 3 : Flattening<jupyter_code>cnn.add(tf.keras.layers.Flatten())<jupyter_output><empty_output><jupyter_text>Step 4 : Full Connection<jupyter_code>cnn.add(tf.keras.layers.Dense(units=128,activation="relu"))
##       units : no of hidden neurons<jupyter_output><empty_output><jupyter_text>Output Layer<jupyter_code>cnn.add(tf.keras.layers.Dense(units=1,activation="sigmoid"))
## sigmoid - binary classification    softmax : multiclass classification<jupyter_output><empty_output><jupyter_text>Training the cnn  Compiling the cnn<jupyter_code>cnn.compile(optimizer='adam', loss='binary_crossentropy', metrics= ['accuracy'])<jupyter_output><empty_output><jupyter_text>Training the CNN on the Training set and evaluation it on the test set<jupyter_code>cnn.fit(x=training_set,validation_data = test_set, epochs= 25)<jupyter_output>WARNING:tensorflow:sample_weight modes were coerced from
  ...
    to  
  ['...']
WARNING:tensorflow:sample_weight modes were coerced from
  ...
    to  
  ['...']
Train for 250 steps, validate for 63 steps
Epoch 1/25
250/250 [==============================] - 100s 398ms/step - loss: 0.6744 - accuracy: 0.5859 - val_loss: 0.6277 - val_accuracy: 0.6615
Epoch 2/25
250/250 [==============================] - 43s 173ms/step - loss: 0.6258 - accuracy: 0.6486 - val_loss: 0.5907 - val_accuracy: 0.6925
Epoch 3/25
250/250 [==============================] - 41s 162ms/step - loss: 0.5836 - accuracy: 0.6896 - val_loss: 0.5334 - val_accuracy: 0.7400
Epoch 4/25
250/250 [==============================] - 40s 162ms/step - loss: 0.5352 - accuracy: 0.7289 - val_loss: 0.5339 - val_accuracy: 0.7515
Epoch 5/25
250/250 [==============================] - 41s 163ms/step - loss: 0.5065 - accuracy: 0.7494 - val_loss: 0.5041 - val_accuracy: 0.7635
Epoch 6/25
250/250 [==============================] - 41s 162ms/ste[...]<jupyter_text>Single Prediction<jupyter_code>import numpy as np
from keras.preprocessing import image
test_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size = [64,64])
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = cnn.predict(test_image)
training_set.class_indices
if result[0][0] == 0:
  print("CAT")
else :
  print("DOG")

import os,datetime
def save_model(model, suffix=None):
  """
  Saves a given model in a models directory and appends a suffix (str)
  for clarity and reuse.
  """
  # Create model directory with current time
  modeldir = os.path.join("",
                         datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
  model_path = modeldir + "-" + suffix + ".h5" # save format of model
  print(f"Saving model to: {model_path}...")
  model.save(model_path)
  return model_path
# Save model to file
save_model(cnn, suffix="catvsdog-model-Adam")

# Load in the full model
def load_model(model_path):
  """
  Loads a saved model from a specified path.
  """
  print(f"Loading saved model from: {model_path}")
  model = tf.keras.models.load_model(model_path)
  return model
model = load_model('20200813-104609-catvsdog-model-Adam.h5')
import numpy as np
from keras.preprocessing import image
test_image = image.load_img('dataset/test_set/dogs/dog.4057.jpg', target_size = [64,64])
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = model.predict(test_image)
#training_set.class_indices
if result[0][0] == 0:
  print("CAT")
else :
  print("DOG")<jupyter_output>DOG
{'fraction_non_alphanumeric': 0.14246173884728103, 'fraction_numerical': 0.048518397915988276, 'mean_word_length': 4.666974169741698, 'pattern_counts': {'":': 0, '<': 51, '<?xml version=': 0, '>': 49, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '307799', 'license': 'Apache-2.0', 'n_tokens_mistral': 2292, 'n_tokens_neox': 2060, 'n_words': 480, 'path': 'catvsdog.ipynb', 'repo_name': 'Abhayparashar31/catvsdog', 'size': '6142'}