keras
Lots of keras
examples, some including CNNs available here: https://github.com/fchollet/keras/tree/master/examples
Specifically, this notebook is based on the following example training a CNN on the MNIST dataset of hand-written digits: https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py
In [1]:
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import tensorflow.contrib.keras as keras
In [2]:
%matplotlib inline
In [3]:
# Dataset of 60,000 28x28 grayscale images of the 10 digits, along with a test set of 10,000 images.
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# input image dimensions and class counts
img_rows, img_cols = 28, 28
num_classes = 10
In [4]:
x_train[0].shape
Out[4]:
In [5]:
y_train[0]
Out[5]:
In [6]:
plt.imshow(x_train[0], cmap=cm.binary)
Out[6]:
In [7]:
# images are expected as 3D tensors with the third dimension containing different image channels; reshape x to a
# 3D tensore with single color channel, the grayscale channel
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train[0].shape
Out[7]:
In [8]:
# convert X to [0,1]
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
In [9]:
y_train[:5]
Out[9]:
In [10]:
# convert to a one hot encoding of the class labels
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
y_train[:5]
Out[10]:
In [11]:
batch_size = 128
epochs = 7 # increasing this would probably make sense but takes longer to compute
In [12]:
# houses a linear stack of layers
model = keras.models.Sequential()
In [13]:
# add layers to the sequential model
model.add(keras.layers.Conv2D(32, # 32 filters/kernels
kernel_size=(3, 3), # filter size of 3x3 pixels
activation='relu',
input_shape=input_shape))
model.add(keras.layers.Conv2D(64, (3, 3), activation='relu'))
model.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))
model.add(keras.layers.Dropout(0.25))
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(128, activation='relu'))
model.add(keras.layers.Dropout(0.5))
model.add(keras.layers.Dense(num_classes, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
The model can be visualized as follows:
In [14]:
keras.utils.plot_model(model, to_file='chapter_9_cnn.png', show_shapes=True)
A convolutional layer 'Conv2D' lookse like this:
A max pooling layer 'MaxPooling2D' lookse like this:
In [15]:
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
Out[15]:
In [16]:
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])