2. Build a cnn model to perform handwritten number
recognition using keras.
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten,
Dense, Dropout
from keras.utils import to_categorical
import matplotlib.pyplot as plt
import numpy as np
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(x_train.shape[0], 28, 28,
1).astype('float32') / 255
x_test = x_test.reshape(x_test.shape[0], 28, 28,
1).astype('float32') / 255
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu',
input_shape=(28, 28, 1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
model.compile(optimizer='adam',
loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(x_train, y_train, epochs=5,
batch_size=128, validation_split=0.1, verbose=2)
test_loss, test_acc = model.evaluate(x_test, y_test,
verbose=0)
print(f"\nTest Accuracy: {test_acc:.4f}, Test Loss:
{test_loss:.4f}")
plt.figure(figsize=(10,4))
plt.subplot(1,2,1)
plt.plot(history.history['accuracy'], label='train acc')
plt.plot(history.history['val_accuracy'], label='val acc')
plt.title('Model Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1,2,2)
plt.plot(history.history['loss'], label='train loss')
plt.plot(history.history['val_loss'], label='val loss')
plt.title('Model Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.tight_layout()
plt.show()
predictions = model.predict(x_test[:9])
predicted_labels = np.argmax(predictions, axis=1)
true_labels = np.argmax(y_test[:9], axis=1)
plt.figure(figsize=(6,6))
for i in range(9):
plt.subplot(3,3,i+1)
plt.imshow(x_test[i].reshape(28,28), cmap='gray')
plt.title(f"Pred: {predicted_labels[i]}, True:
{true_labels[i]}")
plt.axis('off')
plt.tight_layout()
plt.show()
