<jupyter_start><jupyter_text>Introduction to Deep Learning - II Created by [Nimblebox Inc.](https://www.nimblebox.ai/).  Introduction:  Today we will be covering Implementation of Convolutional Neural Networks. A Convolutional Neural Network (ConvNet/CNN) is a Deep Learning algorithm which can take in an input image, assign importance (learnable weights and biases) to various aspects/objects in the image and be able to differentiate one from the other. The pre-processing required in a ConvNet is much lower as compared to other classification algorithms. While in primitive methods filters are hand-engineered, with enough training, ConvNets have the ability to learn these filters/characteristics.  **Downloading Dataset**<jupyter_code>import tensorflow as tf
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
import matplotlib.pyplot as plt

image_index = 7777 # You may select anything up to 60,000

print(y_train[image_index]) # The label is 8
plt.imshow(x_train[image_index], cmap='Greys')
x_train.shape<jupyter_output><empty_output><jupyter_text>**Reshaping and Normalizing the Images**<jupyter_code># Reshaping the array to 4-dims so that it can work with the Keras API
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)

input_shape = (28, 28, 1)

# Making sure that the values are float so that we can get decimal points after division
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')

# Normalizing the RGB codes by dividing it to the max RGB value.
x_train /= 255
x_test /= 255

print('x_train shape:', x_train.shape)
print('Number of images in x_train', x_train.shape[0])
print('Number of images in x_test', x_test.shape[0])<jupyter_output>x_train shape: (60000, 28, 28, 1)
Number of images in x_train 60000
Number of images in x_test 10000<jupyter_text>**Building the Convolutional Neural Network**<jupyter_code># Importing the required Keras modules containing model and layers
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D
# Creating a Sequential Model and adding the layers
model = Sequential()
model.add(Conv2D(28, kernel_size=(3,3), input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten()) # Flattening the 2D arrays for fully connected layers
model.add(Dense(128, activation=tf.nn.relu))
model.add(Dropout(0.2))
model.add(Dense(10,activation=tf.nn.softmax))<jupyter_output><empty_output><jupyter_text>**Compiling and Fitting the Model**<jupyter_code>model.compile(optimizer='adam', 
              loss='sparse_categorical_crossentropy', 
              metrics=['accuracy'])
model.fit(x=x_train,y=y_train, epochs=10)<jupyter_output>Epoch 1/10
1875/1875 [==============================] - 63s 34ms/step - loss: 0.2361 - accuracy: 0.9293
Epoch 2/10
1875/1875 [==============================] - 69s 37ms/step - loss: 0.1094 - accuracy: 0.9672
Epoch 3/10
1875/1875 [==============================] - 68s 36ms/step - loss: 0.0784 - accuracy: 0.9754
Epoch 4/10
1875/1875 [==============================] - 63s 34ms/step - loss: 0.0642 - accuracy: 0.9800
Epoch 5/10
1875/1875 [==============================] - 75s 40ms/step - loss: 0.0512 - accuracy: 0.9837
Epoch 6/10
1875/1875 [==============================] - 66s 35ms/step - loss: 0.0416 - accuracy: 0.9862
Epoch 7/10
1875/1875 [==============================] - 71s 38ms/step - loss: 0.0357 - accuracy: 0.9884
Epoch 8/10
1875/1875 [==============================] - 79s 42ms/step - loss: 0.0322 - accuracy: 0.9895
Epoch 9/10
1875/1875 [==============================] - 83s 44ms/step - loss: 0.0275 - accuracy: 0.9908
Epoch 10/10
1875/1875 [==============================] - 77s 41m[...]<jupyter_text>**Evaluating the Model**<jupyter_code>model.evaluate(x_test, y_test)<jupyter_output>313/313 [==============================] - 9s 28ms/step - loss: 0.0731 - accuracy: 0.9818<jupyter_text>**Prediction**<jupyter_code>image_index = 9999
plt.imshow(x_test[image_index].reshape(28, 28),cmap='Greys')
pred = model.predict(x_test[image_index].reshape(1, 28, 28, 1))
print("Predicted Number:", pred.argmax())<jupyter_output>Predicted Number: 6
{'fraction_non_alphanumeric': 0.1871746332229058, 'fraction_numerical': 0.08400378608613346, 'mean_word_length': 5.656692913385827, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 21, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '339830', 'license': 'MIT', 'n_tokens_mistral': 1694, 'n_tokens_neox': 1408, 'n_words': 390, 'path': 'Day 9 - Introduction to Deep Learning - II/.ipynb_checkpoints/CNN_Keras-checkpoint.ipynb', 'repo_name': 'selvadevan/nimblebox-week2', 'size': '4226'}