image_output_1.png
from keras.layers import  Input,Conv2D,MaxPool2D, UpSampling2D,Dense, Dropout

from keras.models import Model

from tensorflow.keras import layers, losses

from tensorflow.keras import losses

import matplotlib.pyplot as plt

import tensorflow as tf

# Visualization for mnist, cifar10, noisy, denoised/predictions data
def display(rows, cols, a, b, check=False ):
    '''rows: defining no. of rows in figure
      cols: defining no. of colums in figure
      a: train images without noise or noisy_image while test
      prediction
      b: train images with noise or denoised_image based while test 
      prediction
      check: default False for 32*32 cifar10, true for 28*28
      mnist dataset and any predictions
    '''
    # defining a figure 
    f = plt.figure(figsize=(2*cols,2*rows*2)) 
    for i in range(rows):
        for j in range(cols):
            # adding subplot to figure on each iteration
            f.add_subplot(rows*2,cols, (2*i*cols)+(j+1))
            if check:
                plt.imshow(a[i*cols + j].reshape([28,28]),cmap="Blues")
            else:
                plt.imshow(a[i*cols + j])
            plt.axis("off")
        for j in range(cols):
            # adding subplot to figure on each iteration
            f.add_subplot(rows*2,cols,((2*i+1)*cols)+(j+1)) 
            if check:
                plt.imshow(b[i*cols + j].reshape([28,28]),cmap="Blues")
            else:
                plt.imshow(b[i*cols + j])
            plt.axis("off")
            plt.axis("off")
        
    #f.suptitle("Sample Training Data",fontsize=18)
    plt.savefig("ss.png")
    plt.show()

inputs = Input(shape=(28, 28, 1))
x = Conv2D(32, 3, activation='relu', padding='same')(inputs)
x = MaxPool2D()(x)
x = Dropout(0.2)(x)
x = Conv2D(32, 3, activation='relu', padding='same')(x)
encoded = MaxPool2D()(x)
x = Conv2D(32, 3, activation='relu', padding='same')(encoded)
x = UpSampling2D()(x)
x = Dropout(0.2)(x)
x = Conv2D(32, 3, activation='relu', padding='same')(x)
x = UpSampling2D()(x)
decoded = Conv2D(1, 3, activation='sigmoid', padding='same')(x)

from tensorflow.keras import losses
autoencoder1 = Model(inputs, decoded)
autoencoder1.compile(optimizer='adam', loss=losses.binary_crossentropy)
autoencoder1.summary()

history1 = autoencoder1.fit(noisy_train_data, train_data, epochs=50, batch_size=256, shuffle=True, validation_data=(noisy_test_data, test_data))

def plot_diag(history):
    f = plt.figure(figsize=(10,7))
    f.add_subplot()
    #Adding Subplot
    plt.plot(history.epoch, history.history['loss'], label = "loss") # Loss curve for training set
    plt.plot(history.epoch, history.history['val_loss'], label = "val_loss") # Loss curve for validation set

    plt.title("Loss Curve",fontsize=18)
    plt.xlabel("Epochs",fontsize=15)
    plt.ylabel("Loss",fontsize=15)
    plt.grid(alpha=0.3)
    plt.legend()
    plt.savefig("Loss_curve.png")
    plt.show()
plot_diag(history1)

from tensorflow.keras import layers, losses
class Denoise(Model):
    """__init__ constructor in OOP
    This method called when an object is created from the class and 
    it allow the class to initialize the attributes of a class.
    super()function used to give access to 
    methods and properties of a parent or sibling class
    """
    def __init__(self):
        super(Denoise, self).__init__()
        self.encoder = tf.keras.Sequential([layers.Input(shape=(28, 28, 1)), layers.Conv2D(16, (3, 3), activation='relu', padding='same', strides=2), layers.Conv2D(8, (3, 3), activation='relu', padding='same', strides=2)])
        self.decoder = tf.keras.Sequential([layers.Conv2DTranspose(8, kernel_size=3, strides=2, activation='relu', padding='same'), layers.Conv2DTranspose(16, kernel_size=3, strides=2, activation='relu', padding='same'), layers.Conv2D(1, kernel_size=(3, 3), activation='sigmoid', padding='same')])
    def call(self, x):
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return decoded
autoencoder = Denoise()

autoencoder.compile(optimizer='rmsprop', loss=losses.MeanSquaredError())

history = autoencoder.fit(noisy_train_data, train_data, epochs=10, batch_size=256, shuffle=True, validation_data=(noisy_test_data, test_data))

plot_diag(history)