In this notebook, we build a deep, convolutional, MNIST-classifying network inspired by LeNet-5 and this example code.
In [1]:
import numpy as np
np.random.seed(42)
In [2]:
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.layers import Flatten, Conv2D, MaxPooling2D # new!
In [3]:
(X_train, y_train), (X_test, y_test) = mnist.load_data()
In [4]:
X_train = X_train.reshape(60000, 28, 28, 1).astype('float32')
X_test = X_test.reshape(10000, 28, 28, 1).astype('float32')
In [5]:
X_train /= 255
X_test /= 255
In [6]:
n_classes = 10
y_train = keras.utils.to_categorical(y_train, n_classes)
y_test = keras.utils.to_categorical(y_test, n_classes)
In [7]:
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(n_classes, activation='softmax'))
In [8]:
model.summary()
In [8]:
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
In [9]:
model.fit(X_train, y_train, batch_size=128, epochs=20, verbose=1, validation_data=(X_test, y_test))
Out[9]:
In [ ]: