<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Convolutional neural networks (CNNs) in keras
Lots of keras examples, some including CNNs available here
Step1:  Dataset pre-processing
Step2:  Specifying the CNN model
Step3:  The model can be visualized as follows
Step4:  A convolutional layer 'Conv2D' lookse like this
Step5:  Testing the model
<ASSISTANT_TASK:>
Python Code:
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import tensorflow.contrib.keras as keras
%matplotlib inline
Explanation: Convolutional neural networks (CNNs) in 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
End of explanation
# 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
x_train[0].shape
y_train[0]
plt.imshow(x_train[0], cmap=cm.binary)
# 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
# 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')
y_train[:5]
# 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]
Explanation: Dataset pre-processing
End of explanation
batch_size = 128
epochs = 7  # increasing this would probably make sense but takes longer to compute
# houses a linear stack of layers
model = keras.models.Sequential()
# 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'])
Explanation: Specifying the CNN model
End of explanation
keras.utils.plot_model(model, to_file='chapter_9_cnn.png', show_shapes=True)
Explanation: The model can be visualized as follows:
End of explanation
model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))
Explanation: A convolutional layer 'Conv2D' lookse like this:
A max pooling layer 'MaxPooling2D' lookse like this:
Training the model
End of explanation
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
Explanation: Testing the model
End of explanation
<END_TASK>