Just as we learned how to implement an autoencoder in the previous section, implementing a CAE is also the same, but the only difference is here we use convolutional layers in the encoder and decoder instead of a feedforward network. We will use the same MNIST dataset to reconstruct the images using CAE.
Import the libraries:
import warnings
warnings.filterwarnings('ignore')
#modelling
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from tensorflow.keras import backend as K
#plotting
import matplotlib.pyplot as plt
%matplotlib inline
#dataset
from keras.datasets import mnist
import numpy as np
Read and reshape the dataset:
(x_train, _), (x_test, _) = mnist.load_data()
# Normalize the dataset
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
# reshape
x_train = np.reshape(x_train, (len(x_train), 28, 28, 1))
x_test = np.reshape(x_test, (len(x_test), 28, 28, 1))
Let's define the shape of our input image:
input_image = Input(shape=(28, 28, 1))