10)Build a Convolution Neural Network for MNIST Hand written Digit Classification.
Code:
importkeras
fromkeras.models import Sequential
fromkeras.layers import Dense,Conv2D,MaxPooling2D,Flatten
fromkeras.datasets import mnist
fromkeras.utils import to_categorical
frommatplotlib import pyplot as plt
(xt, yt), (xte, yte) = mnist.load_data()
'''for i in range(20):
plt.subplot(5,4,i+1)
plt.imshow(xt[i])
plt.title("Digits:{}".format(yt[i]))
plt.subplots_adjust(hspace=0.5)
plt.axis('off')'''
# Preprocess the data
xt = xt.reshape((xt.shape[0], 28, 28)).astype('float32') / 255
xte = xte.reshape((xte.shape[0], 28, 28)).astype('float32') / 255
yt = to_categorical(yt)
yte = to_categorical(yte)
# Define the CNN model
n=Sequential()
n.add(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
n.add(MaxPooling2D((2, 2)))
n.add(Conv2D(64, (3, 3), activation='relu'))
n.add(MaxPooling2D((2, 2)))
n.add(Conv2D(64, (3, 3), activation='relu'))
n.add(Flatten())
n.add(Dense(64, activation='relu'))
n.add(Dense(10, activation='softmax'))
# Compile the model
n.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])
# Train the modelhistory =
importnumpy as np
n.fit(xt, yt,epochs=2)
'''plt.imshow(xte[0])
plt.title("Actual value:{}".format(yte[0]))'''
p=n.predict(xte)
plt.axis('off')
ifnp.argmax(yte[0])==np.argmax(p[0]):
print("correct p")
else:
print("incorrect cp")
# Evaluate the model
test_loss, test_acc = n.evaluate(xte, yte)
print('Test accuracy:', test_acc)
Output:
Test accuracy:97.7