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.

Chapter 3

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

# generate corrupted MNIST images by adding noise with normal dist

# centered at 0.5 and std=0.5

noise = np.random.normal(loc=0.5, scale=0.5, size=x_train.shape)

x_train_noisy = x_train + noise

noise = np.random.normal(loc=0.5, scale=0.5, size=x_test.shape)

x_test_noisy = x_test + noise

# adding noise may exceed normalized pixel values>1.0 or <0.0

# clip pixel values >1.0 to 1.0 and <0.0 to 0.0

x_train_noisy = np.clip(x_train_noisy, 0., 1.)

x_test_noisy = np.clip(x_test_noisy, 0., 1.)

# network parameters

input_shape = (image_size, image_size, 1)

batch_size = 32

kernel_size = 3

latent_dim = 16

# encoder/decoder number of CNN layers and filters per layer

layer_filters = [32, 64]

# build the autoencoder model

# first build the encoder model

inputs = Input(shape=input_shape, name='encoder_input')

x = inputs

# stack of Conv2D(32)-Conv2D(64)

for filters in layer_filters:

x = Conv2D(filters=filters,

kernel_size=kernel_size,

strides=2,

activation='relu',

padding='same')(x)

# shape info needed to build decoder model

# so we don't do hand computation

# the input to the decoder's first Conv2DTranspose

# will have this shape

# shape is (7, 7, 64) which can be processed by

[ 87 ]

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

Saved successfully!

Ooh no, something went wrong!