Defining the model's architecture

Once the data preparation is completed, the next step is to define the model and create it, so let's create the model:

model_m = Sequential()

The preceding line will create a sequential model that will process the layers in the sequential way they are arranged. There are two ways to build Keras models, sequential and functional:

  • The sequential API: This allows us to create models layer-by-layer. Through this, we cannot create models that share layers or have multiple input or output.
  • The functional API: This allows us to create models that are more than and can have complex connection layers—you can literally connect from any layer to any other layer:
model_m.add(Conv2D(32, (5, 5), input_shape=(1,28,28), activation='relu'))

The input shape parameter should be the shape of 1 sample. In this case, it's the same (1, 28, 28), which corresponds to the (depth, width, height) of each digit image.

But what do the other parameters represent? They correspond to the number of convolutional filters to use, the number of rows in each convolution kernel, and the number of columns in each convolution kernel, respectively:

model_m.add(MaxPooling2D(pool_size=(2, 2)))

MaxPooling2D is a way to reduce the number of parameters in our model by sliding a 2 x 2 pooling filter across the previous layer and taking the max of the 4 values in the 2 x 2 filter:

model_m.add(Dropout(0.5))

This is a method for regularizing our model in order to prevent overfitting:

model_m.add(Conv2D(64, (3, 3), activation='relu'))
model_m.add(MaxPooling2D(pool_size=(2, 2)))
model_m.add(Dropout(0.2))
model_m.add(Conv2D(128, (1, 1), activation='relu'))
model_m.add(MaxPooling2D(pool_size=(2, 2)))
model_m.add(Dropout(0.2))
model_m.add(Flatten())
model_m.add(Dense(128, activation='relu'))
model_m.add(Dense(num_classes, activation='softmax'))
print(model_m.summary())

Once you run the preceding lines of code, the model architecture's names of the layers will be printed in the console:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset