<jupyter_start><jupyter_text>Convolutional Neural Networks (CNN)- A convolutional neural network is a class of deep neural networks, most commonly applied to analyzing visual imagery. They are also known as shift invariant or space invariant artificial neural networks, based on their shared-weights architecture and translation invariance characteristics.![image.png](attachment:image.png)- Steps for CNN;        - Step 1 : Convolution        - Step 2 : Max Pooling        - Step 3 : Flattening        - Step 4 : Full Connection Step 1 : Convolution![image-2.png](attachment:image-2.png)- In mathematics convolution is a mathematical operation on two functions that produces a third function expressing how the shape of one is modified by the other. The term convolution refers to both the result function and to the process of computing it.- It is a combined integration of 2 function and it shows how one function modifies the other.**Step 2 : Max Pooling**- Max pooling is a type of operation that is typically added to CNNs following individual convolutional layers. When added to a model, max pooling reduces the dimensionality of images by reducing the number of pixels in the output from the previous convolutional layer.**Step 3 : Flattening**![image-3.png](attachment:image-3.png)**Step 4 : Full Connection**![image-4.png](attachment:image-4.png)**Softmax & Cross-Entropy**![image-6.png](attachment:image-6.png) **Importing the Libraries**<jupyter_code># Importing Libraries and Packages
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator<jupyter_output><empty_output><jupyter_text>Part - 1 : Data Preprocessing **Preprocessing the Training Set**<jupyter_code># Transformation is needed, because to avoid over fitting
# Transformation are some geometrical transformation or some zoom or some rotation on image.
train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)

# Trainging Set
training_set = train_datagen.flow_from_directory('D:\\Programming Language\\Machine Learning\\dataset\\training_set',
                                                 target_size = (64, 64),
                                                 batch_size = 32,
                                                 class_mode = 'binary')<jupyter_output>Found 8000 images belonging to 2 classes.<jupyter_text>**Preprocessing the Test Set**<jupyter_code># Transformation is needed, because to avoid over fitting
# Transformation are some geometrical transformation or some zoom or some rotation on image.
test_datagen = ImageDataGenerator(rescale = 1./255)

# Test Set
test_set = test_datagen.flow_from_directory('D:\\Programming Language\\Machine Learning\\dataset\\test_set',
                                            target_size = (64, 64),
                                            batch_size = 32,
                                            class_mode = 'binary')<jupyter_output>Found 2000 images belonging to 2 classes.<jupyter_text>Part - 2 : Building the CNN **Initialising the CNN**<jupyter_code>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]))<jupyter_output><empty_output><jupyter_text>**Step 2 : Pooling**<jupyter_code>cnn.add(tf.keras.layers.MaxPool2D(pool_size = 2, strides = 2))<jupyter_output><empty_output><jupyter_text>**Adding a second convolution**<jupyter_code># Convolution
cnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu'))

# Pooling
cnn.add(tf.keras.layers.MaxPool2D(pool_size=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'))<jupyter_output><empty_output><jupyter_text>**Step 5 : Output Layer**<jupyter_code>cnn.add(tf.keras.layers.Dense(units = 1, activation = 'sigmoid'))<jupyter_output><empty_output><jupyter_text>Part - 3 : 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 eveluating on the Test Set**<jupyter_code>cnn.fit(x = training_set, validation_data = test_set, epochs = 25)<jupyter_output>Epoch 1/25
250/250 [==============================] - 312s 1s/step - loss: 0.6689 - accuracy: 0.5928 - val_loss: 0.6162 - val_accuracy: 0.6870
Epoch 2/25
250/250 [==============================] - 67s 267ms/step - loss: 0.6094 - accuracy: 0.6658 - val_loss: 0.5777 - val_accuracy: 0.7095
Epoch 3/25
250/250 [==============================] - 66s 266ms/step - loss: 0.5782 - accuracy: 0.6977 - val_loss: 0.5481 - val_accuracy: 0.7215
Epoch 4/25
250/250 [==============================] - 66s 264ms/step - loss: 0.5416 - accuracy: 0.7279 - val_loss: 0.5724 - val_accuracy: 0.7100
Epoch 5/25
250/250 [==============================] - 65s 260ms/step - loss: 0.5296 - accuracy: 0.7344 - val_loss: 0.5017 - val_accuracy: 0.7560
Epoch 6/25
250/250 [==============================] - 66s 264ms/step - loss: 0.4957 - accuracy: 0.7591 - val_loss: 0.5419 - val_accuracy: 0.7445
Epoch 7/25
250/250 [==============================] - 66s 264ms/step - loss: 0.4830 - accuracy: 0.7621 - val_loss: 0.4912 - val_accu[...]<jupyter_text>Part - 4 : Making a Single Prediction<jupyter_code># Import Libraries and Packages
# Numpy allows us to work with array.
import numpy as np

from keras.preprocessing import image

test_image = image.load_img('D:/Programming Language/Machine Learning/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] == 1:
    prediction = 'Dog'
else:
    prediction = "Cat"
    
print(prediction)<jupyter_output>Dog
{'fraction_non_alphanumeric': 0.13748399487836108, 'fraction_numerical': 0.052176696542893725, 'mean_word_length': 3.88203125, 'pattern_counts': {'":': 0, '<': 49, '<?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': 15, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '439967', 'license': 'MIT', 'n_tokens_mistral': 2147, 'n_tokens_neox': 1872, 'n_words': 507, 'path': 'Convolutional Neural Networks (CNN).ipynb', 'repo_name': 'dshah98/Machine_Learning_with_Python', 'size': '6248'}