16.03.2021 Views

Advanced Deep Learning with Keras

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Deep Neural Networks

from keras.utils import plot_model

# load MNIST dataset

(x_train, y_train), (x_test, y_test) = mnist.load_data()

# compute the number of labels

num_labels = len(np.unique(y_train))

# convert to one-hot vector

y_train = to_categorical(y_train)

y_test = to_categorical(y_test)

# reshape and normalize input images

image_size = x_train.shape[1]

x_train = np.reshape(x_train,[-1, image_size, image_size, 1])

x_test = np.reshape(x_test,[-1, image_size, image_size, 1])

x_train = x_train.astype('float32') / 255

x_test = x_test.astype('float32') / 255

# network parameters

input_shape = (image_size, image_size, 1)

batch_size = 32

kernel_size = 3

dropout = 0.4

n_filters = 32

# left branch of Y network

left_inputs = Input(shape=input_shape)

x = left_inputs

filters = n_filters

# 3 layers of Conv2D-Dropout-MaxPooling2D

# number of filters doubles after each layer (32-64-128)

for i in range(3):

x = Conv2D(filters=filters,

kernel_size=kernel_size,

padding='same',

activation='relu')(x)

x = Dropout(dropout)(x)

x = MaxPooling2D()(x)

filters *= 2

# right branch of Y network

right_inputs = Input(shape=input_shape)

y = right_inputs

filters = n_filters

# 3 layers of Conv2D-Dropout-MaxPooling2D

# number of filters doubles after each layer (32-64-128)

for i in range(3):

y = Conv2D(filters=filters,

kernel_size=kernel_size,

[ 46 ]

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

Saved successfully!

Ooh no, something went wrong!