Skip to content

Commit 02a7c9a

Browse files
committed
Added Mnist using CNN
1 parent d39377a commit 02a7c9a

File tree

1 file changed

+58
-0
lines changed
  • Machine_Learning/src/MNIST_using_CNN

1 file changed

+58
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import numpy as np
2+
import tensorflow as tf
3+
import matplotlib.pyplot as plt
4+
import cv2
5+
6+
# CNN Model
7+
def create_model():
8+
model = tf.keras.models.Sequential([
9+
tf.keras.layers.Conv2D(16, (3,3), activation="relu", input_shape=(28,28,1)),
10+
tf.keras.layers.MaxPooling2D((2,2)),
11+
tf.keras.layers.Conv2D(32, (2,2), activation="relu"),
12+
tf.keras.layers.MaxPooling2D((2,2)),
13+
tf.keras.layers.Flatten(),
14+
tf.keras.layers.Dense(64, activation="relu"),
15+
tf.keras.layers.Dropout(0.3),
16+
tf.keras.layers.Dense(10, activation="softmax")
17+
])
18+
return model
19+
20+
# Plot images with labels
21+
def plot(subset_x, subset_y):
22+
for i in range(len(subset_y)):
23+
plt.figure(figsize=(10,20))
24+
ax = plt.subplot(len(subset_y)/2,2,i+1)
25+
img = subset_x[i]
26+
ax.imshow(img)
27+
plt.show()
28+
print("LABEL : ",subset_y[i])
29+
print()
30+
31+
# Load Mnist dataset from tensorflow datasets
32+
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
33+
34+
# Normalize the pixel values and convert the lables to one-hot vectors
35+
x_train = x_train/255.
36+
x_test = x_test/255.
37+
x_train = x_train.reshape((-1,28,28,1))
38+
x_test = x_test.reshape((-1,28,28,1))
39+
y_train = tf.one_hot(y_train, depth=10)
40+
y_test = tf.one_hot(y_test, depth=10)
41+
42+
# Create and compile the Model
43+
my_model = create_model()
44+
my_model.compile(optimizer = tf.keras.optimizers.Adam(lr=0.001), loss="categorical_crossentropy", metrics=["accuracy"])
45+
46+
# Fit the created model and store the information for plotting of loss and accuracy curves
47+
history = my_model.fit(x_train, y_train, validation_split=0.1, epochs=5, batch_size=32, shuffle=True, verbose=1)
48+
49+
# Evaluate the model using the test data
50+
loss, acc = my_model.evaluate(x_test, y_test)
51+
52+
# Make Predictions
53+
y_predictions = my_model.predict_classes(x_test)
54+
55+
subset_x = x_test[0:10]
56+
subset_y = y_predictions[0:10]
57+
plot(subset_x, subset_y)
58+

0 commit comments

Comments
 (0)