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.

Autoencoders

4. Let us now define our encoder. The encoder consists of three convolutional

layers, each followed by a max pooling layer. Since we are using the MNIST

dataset the shape of the input image is 28 × 28 (single channel) and the

output image is of size 4 × 4 (and since the last convolutional layer has 16

filters, the image has 16 channels):

class Encoder(K.layers.Layer):

def __init__(self, filters):

super(Encoder, self).__init__()

self.conv1 = Conv2D(filters=filters[0], kernel_size=3,

strides=1, activation='relu', padding='same')

self.conv2 = Conv2D(filters=filters[1], kernel_size=3,

strides=1, activation='relu', padding='same')

self.conv3 = Conv2D(filters=filters[2], kernel_size=3,

strides=1, activation='relu', padding='same')

self.pool = MaxPooling2D((2, 2), padding='same')

def call(self, input_features):

x = self.conv1(input_features)

#print("Ex1", x.shape)

x = self.pool(x)

#print("Ex2", x.shape)

x = self.conv2(x)

x = self.pool(x)

x = self.conv3(x)

x = self.pool(x)

return x

5. Next comes the decoder. It is the exact opposite of the encoder in design, and

instead of max pooling we are using upsampling to increase the size back.

Notice the commented print statements: you can use them to understand

how the shape gets modified after each step. Also notice both encoder and

decoder are still classes based on the TensorFlow Keras Layers class, but

now they have multiple layers inside them. So now you know how to build a

complex custom layer:

class Decoder(K.layers.Layer):

def __init__(self, filters):

super(Decoder, self).__init__()

self.conv1 = Conv2D(filters=filters[2], kernel_size=3,

strides=1, activation='relu', padding='same')

self.conv2 = Conv2D(filters=filters[1], kernel_size=3,

strides=1, activation='relu', padding='same')

self.conv3 = Conv2D(filters=filters[0], kernel_size=3,

strides=1, activation='relu', padding='valid')

[ 362 ]

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

Saved successfully!

Ooh no, something went wrong!