# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/sudar-coder321/CNN_on_MNIST_Dataset/blob/main/CNN_MNIST.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + id="dUTb9J_NEEyY"
import tensorflow as tf

# + id="JpvHlp0UGHBD"
mnist = tf.keras.datasets.mnist
(x_train,y_train),(x_test,y_test) = mnist.load_data()

# + id="lrxApFXYRMc7" colab={"base_uri": "https://localhost:8080/", "height": 282} outputId="e9580b13-69f7-4cec-b826-66dae5031ecc"
import matplotlib.pyplot as plt
plt.imshow(x_train[0],cmap = 'gray')
print(y_train[0])
plt.show()

# + id="j5QF6i3nSZu3"
# Reshape the image to 4 dimension
x_train = x_train.reshape(60000,28,28,1)
x_test = x_test.reshape(10000,28,28,1)

# + id="uIozdDvCX92e" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="1ca9dea3-48a2-4062-eec3-eb0feae7898d"
x_train.shape
y_train.shape

# + id="m5MwAGLRSzwE"
# One Hot Encoding vs Label Encoding
from tensorflow.keras.utils import to_categorical

# + id="M2k2o296TRce" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="c942105f-1400-4419-a2e6-644d97c1e1f6"
y_train

# + id="AKZ0GyL2TUbX" colab={"base_uri": "https://localhost:8080/", "height": 50} outputId="b1c78310-2f90-4818-92a6-be4180f341d3"
print(y_train[567])
y_cat_train = to_categorical(y_train)
y_cat_test = to_categorical(y_test)
y_cat_train[567]

# + id="PRpd2jOMTZiA"
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Conv2D,MaxPool2D,Flatten

# + id="zWBqDa3fVJQd"
model = Sequential()

# COnvolutional Layer
model.add(Conv2D(filters = 32,kernel_size=(4,4),input_shape = (28,28,1),activation = 'relu'))
# Pooling Layer
model.add(MaxPool2D(pool_size=(2,2)))

model.add(Conv2D(filters = 32,kernel_size=(4,4),input_shape = (28,28,1),activation = 'relu'))
# Pooling Layer
model.add(MaxPool2D(pool_size=(2,2)))
# Flatten
model.add(Flatten())

# 128 Neurons in 1st Dense Layer
model.add(Dense(512,activation='relu'))
model.add(Dense(128,activation='relu'))
#Output Layer
model.add(Dense(10,activation='softmax'))

# + id="niI4nPmSWGL0"
model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics = ['accuracy'])

# + id="1LPjMvudXXx6" colab={"base_uri": "https://localhost:8080/", "height": 420} outputId="b9184728-6254-42aa-dfc1-6357689570e4"
model.summary()

# + id="dYc-c9vCXaWS" colab={"base_uri": "https://localhost:8080/", "height": 202} outputId="9bfd5bc0-e414-4d4e-cf4d-0462d2f17236"
model.fit(x_train,y_cat_train,epochs = 5) # batch_size =32

# + id="TRIBhZepSEfl"


StarcoderdataJupyterScriptsDedupFiltered