09.05.2023 Views

pdfcoffee

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4

Where pool_size=(2, 2) is a tuple of two integers representing the factors by

which the image is vertically and horizontally downscaled. So (2, 2) will halve the

image in each dimension, and strides=(2, 2) is the stride used for processing.

Now, let us review the code. First, we import a number of modules:

import tensorflow as tf

from tensorflow.keras import datasets, layers, models, optimizers

# network and training

EPOCHS = 5

BATCH_SIZE = 128

VERBOSE = 1

OPTIMIZER = tf.keras.optimizers.Adam()

VALIDATION_SPLIT=0.95

IMG_ROWS, IMG_COLS = 28, 28 # input image dimensions

INPUT_SHAPE = (IMG_ROWS, IM G_COLS, 1)

NB_CLASSES = 10 # number of outputs = number of digits

Then we define the LeNet network:

#define the convnet

def build(input_shape, classes):

model = models.Sequential()

We have a first convolutional stage with rectified linear unit (ReLU) activations

followed by a max pooling. Our net will learn 20 convolutional filters, each one of

which with a size of 5×5. The output dimension is the same as the input shape, so it

will be 28×28. Note that since Convolution2D is the first stage of our pipeline, we

are also required to define its input_shape. The max pooling operation implements

a sliding window that slides over the layer and takes the maximum of each region

with a step of 2 pixels both vertically and horizontally:

# CONV => RELU => POOL

model.add(layers.Convolution2D(20, (5, 5), activation='relu', input_

shape=input_shape))

model.add(layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))

Then there is a second convolutional stage with ReLU activations, followed again

by a max pooling layer. In this case we increase the number of convolutional filters

learned to 50 from the previous 20. Increasing the number of filters in deeper layers

is a common technique used in deep learning:

# CONV => RELU => POOL

model.add(layers.Convolution2D(50, (5, 5), activation='relu'))

model.add(layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))

[ 115 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!