<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Deep Convolutional Generative Adversarial Network
Learning Objectives
Build a GAN architecture (consisting of a generator and discriminator) in Keras 
Define the loss for the generator and discriminator
Define a training step for the GAN using tf.GradientTape() and @tf.function
Train the GAN on the MNIST dataset
Introduction
This notebook demonstrates how to build and train a Generative Adversarial Network (GAN) to generate images of handwritten digits using a Deep Convolutional Generative Adversarial Network (DCGAN).
GANs consist of two models which are trained simultaneously through an adversarial process. A generator ("the artist") learns to create images that look real, while a discriminator ("the art critic") learns to tell real images apart from fakes.
During training, the generator progressively becomes better at creating images that look real, while the discriminator becomes better at recognizing fake images. The process reaches equilibrium when the discriminator can no longer distinguish real images from fakes.
In this notebook we'll build a GAN to generate MNIST digits. This notebook demonstrates this process on the MNIST dataset. The following animation shows a series of images produced by the generator as it was trained for 50 epochs. The images begin as random noise, and increasingly resemble hand written digits over time.
Import TensorFlow and other libraries
Step1:  Load and prepare the dataset
For this notebook, we will use the MNIST dataset to train the generator and the discriminator. The generator will generate handwritten digits resembling the MNIST data.
Step2:  Next, we define our input pipeline using tf.data. The pipeline below reads in train_images as tensor slices and then shuffles and batches the examples for training.
Step3:  Create the generator and discriminator models
Both our generator and discriminator models will be defined using the Keras Sequential API.
The Generator
The generator uses tf.keras.layers.Conv2DTranspose (upsampling) layers to produce an image from a seed (random noise). We will start with a Dense layer that takes this seed as input, then upsample several times until you reach the desired image size of 28x28x1.
Exercise. Complete the code below to create the generator model. Start with a dense layer that takes as input random noise. We will create random noise using tf.random.normal([1, 100]). Use tf.keras.layers.Conv2DTranspose over multiple layers to upsample the random noise from dimension 100 to ultimately dimension 28x28x1 (the shape of our original MNIST digits).
Hint
Step4:  Let's use the (as yet untrained) generator to create an image.
Step5:  The Discriminator
Next, we will build the discriminator. The discriminator is a CNN-based image classifier. It should take in an image of shape 28x28x1 and return a single classification indicating if that image is real or not.
Exercise. Complete the code below to create the CNN-based discriminator model. Your model should be binary classifier which takes as input a tensor of shape 28x28x1. Experiment with different stacks of convolutions, activation functions, and/or dropout.
Step6:  Using .summary() we can have a high-level summary of the generator and discriminator models.
Step7:  Let's use the (as yet untrained) discriminator to classify the generated images as real or fake. The model will be trained to output positive values for real images, and negative values for fake images.
Step8:  Define the loss and optimizers
Next, we will define the loss functions and optimizers for both the generator and discriminaotr models. Both the generator and discriminator will use the BinaryCrossentropy.
Step9:  Discriminator loss
The method below quantifies how well the discriminator is able to distinguish real images from fakes. 
Recall, when training the discriminator (i.e. holding the generator fixed) the loss function has two parts
Step10:  Generator loss
The generator's loss quantifies how well it was able to trick the discriminator. Intuitively, if the generator is performing well, the discriminator will classify the fake images as real (or 1). Here, we will compare the discriminators decisions on the generated images to an array of 1s.
Exercise.
Complete the code to return the cross-entropy loss of the generator's output.
Step11:  Optimizers for the geneerator and discriminator
Note that we must define two separete optimizers for the discriminator and the generator optimizers since we will train two networks separately.
Step12:  Save checkpoints
This notebook also demonstrates how to save and restore models, which can be helpful in case a long running training task is interrupted.
Step13:  Define the training loop
Next, we define the training loop for training our GAN. Below we set up global variables for training.
Step14:  The training loop begins with generator receiving a random seed as input. That seed is used to produce an image. The discriminator is then used to classify real images (drawn from the training set) and fakes images (produced by the generator). The loss is calculated for each of these models, and the gradients are used to update the generator and discriminator.
Exercise.
Complete the code below to define the training loop for our GAN. Notice the use of tf.function below. This annotation causes the function train_step to be "compiled". The train_step function takes as input a batch of images. In the rest of the function,
- generated_images is created using the generator function with noise as input
- apply the discriminator model to the images and generated_images to create the real_output and fake_output (resp.)
- define the gen_loss and disc_loss using the methods you defined above.
- compute the gradients of the generator and the discriminator using gen_tape and disc_tape (resp.)
Lastly, we use the .apply_gradients method to make a gradient step for the generator_optimizer and discriminator_optimizer
Step15:  We use the train_step function above to define training of our GAN. Note here, the train function takes as argument the tf.data dataset and the number of epochs for training.
Step16:  Generate and save images.
We'll use a small helper function to generate images and save them.
Step17:  Train the model
Call the train() method defined above to train the generator and discriminator simultaneously. Note, training GANs can be tricky. It's important that the generator and discriminator do not overpower each other (e.g., that they train at a similar rate).
At the beginning of the training, the generated images look like random noise. As training progresses, the generated digits will look increasingly real. After about 50 epochs, they resemble MNIST digits. This may take about one ot two minutes / epoch.
Step18:  Restore the latest checkpoint.
Step19:  Create a GIF
Lastly, we'll create a gif that shows the progression of our produced images through training.
Step20:  Use imageio to create an animated gif using the images saved during training.
<ASSISTANT_TASK:>
Python Code:
from __future__ import absolute_import, division, print_function, unicode_literals
try:
  %tensorflow_version 2.x
except Exception:
  pass
import tensorflow as tf
tf.__version__
# To generate GIFs
!python3 -m pip install -q imageio
import glob
import imageio
import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
from tensorflow.keras import layers
import time
from IPython import display
Explanation: Deep Convolutional Generative Adversarial Network
Learning Objectives
Build a GAN architecture (consisting of a generator and discriminator) in Keras 
Define the loss for the generator and discriminator
Define a training step for the GAN using tf.GradientTape() and @tf.function
Train the GAN on the MNIST dataset
Introduction
This notebook demonstrates how to build and train a Generative Adversarial Network (GAN) to generate images of handwritten digits using a Deep Convolutional Generative Adversarial Network (DCGAN).
GANs consist of two models which are trained simultaneously through an adversarial process. A generator ("the artist") learns to create images that look real, while a discriminator ("the art critic") learns to tell real images apart from fakes.
During training, the generator progressively becomes better at creating images that look real, while the discriminator becomes better at recognizing fake images. The process reaches equilibrium when the discriminator can no longer distinguish real images from fakes.
In this notebook we'll build a GAN to generate MNIST digits. This notebook demonstrates this process on the MNIST dataset. The following animation shows a series of images produced by the generator as it was trained for 50 epochs. The images begin as random noise, and increasingly resemble hand written digits over time.
Import TensorFlow and other libraries
End of explanation
(train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
train_images = (train_images - 127.5) / 127.5 # Normalize the images to [-1, 1]
BUFFER_SIZE = 60000
BATCH_SIZE = 256
Explanation: Load and prepare the dataset
For this notebook, we will use the MNIST dataset to train the generator and the discriminator. The generator will generate handwritten digits resembling the MNIST data.
End of explanation
# Batch and shuffle the data
train_dataset = tf.data.Dataset.from_tensor_slices(train_images)
train_dataset = train_dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
Explanation: Next, we define our input pipeline using tf.data. The pipeline below reads in train_images as tensor slices and then shuffles and batches the examples for training.
End of explanation
#TODO 1
def make_generator_model():
    model = tf.keras.Sequential()
    
    # TODO: Your code goes here.
    
    assert model.output_shape == (None, 28, 28, 1)
    return model
Explanation: Create the generator and discriminator models
Both our generator and discriminator models will be defined using the Keras Sequential API.
The Generator
The generator uses tf.keras.layers.Conv2DTranspose (upsampling) layers to produce an image from a seed (random noise). We will start with a Dense layer that takes this seed as input, then upsample several times until you reach the desired image size of 28x28x1.
Exercise. Complete the code below to create the generator model. Start with a dense layer that takes as input random noise. We will create random noise using tf.random.normal([1, 100]). Use tf.keras.layers.Conv2DTranspose over multiple layers to upsample the random noise from dimension 100 to ultimately dimension 28x28x1 (the shape of our original MNIST digits).
Hint: Experiment with using BatchNormalization or different activation functions like LeakyReLU.
End of explanation
generator = make_generator_model()
noise = tf.random.normal([1, 100])
generated_image = generator(noise, training=False)
plt.imshow(generated_image[0, :, :, 0], cmap='gray')
Explanation: Let's use the (as yet untrained) generator to create an image.
End of explanation
#TODO 1.
def make_discriminator_model():
    model = tf.keras.Sequential()
    
    # TODO: Your code goes here.
    
    assert model.output_shape == (None, 1)
    return model
Explanation: The Discriminator
Next, we will build the discriminator. The discriminator is a CNN-based image classifier. It should take in an image of shape 28x28x1 and return a single classification indicating if that image is real or not.
Exercise. Complete the code below to create the CNN-based discriminator model. Your model should be binary classifier which takes as input a tensor of shape 28x28x1. Experiment with different stacks of convolutions, activation functions, and/or dropout.
End of explanation
make_generator_model().summary()
make_discriminator_model().summary()
Explanation: Using .summary() we can have a high-level summary of the generator and discriminator models.
End of explanation
discriminator = make_discriminator_model()
decision = discriminator(generated_image)
print(decision)
Explanation: Let's use the (as yet untrained) discriminator to classify the generated images as real or fake. The model will be trained to output positive values for real images, and negative values for fake images.
End of explanation
# This method returns a helper function to compute cross entropy loss
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
Explanation: Define the loss and optimizers
Next, we will define the loss functions and optimizers for both the generator and discriminaotr models. Both the generator and discriminator will use the BinaryCrossentropy.
End of explanation
#TODO 2
def discriminator_loss(real_output, fake_output):
    real_loss = # TODO: Your code goes here.
    fake_loss = # TODO: Your code goes here.
    total_loss = # TODO: Your code goes here.
    return total_loss
Explanation: Discriminator loss
The method below quantifies how well the discriminator is able to distinguish real images from fakes. 
Recall, when training the discriminator (i.e. holding the generator fixed) the loss function has two parts: the loss when sampling from the real data and the loss when sampling from the fake data. The function below compares the discriminator's predictions on real images to an array of 1s, and the discriminator's predictions on fake (generated) images to an array of 0s.
Exercise.
Complete the code in the method below. The real_loss should return the cross-entropy for the discriminator's predictions on real images and the fake_loss should return the cross-entropy for the discriminator's predictions on fake images.
End of explanation
#TODO 2
def generator_loss(fake_output):
    return # Your code goes here.
Explanation: Generator loss
The generator's loss quantifies how well it was able to trick the discriminator. Intuitively, if the generator is performing well, the discriminator will classify the fake images as real (or 1). Here, we will compare the discriminators decisions on the generated images to an array of 1s.
Exercise.
Complete the code to return the cross-entropy loss of the generator's output.
End of explanation
generator_optimizer = tf.keras.optimizers.Adam(1e-4)
discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
Explanation: Optimizers for the geneerator and discriminator
Note that we must define two separete optimizers for the discriminator and the generator optimizers since we will train two networks separately.
End of explanation
checkpoint_dir = "./gan_training_checkpoints"
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")
checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,
                                 discriminator_optimizer=discriminator_optimizer,
                                 generator=generator,
                                 discriminator=discriminator)
Explanation: Save checkpoints
This notebook also demonstrates how to save and restore models, which can be helpful in case a long running training task is interrupted.
End of explanation
EPOCHS = 50
noise_dim = 100
num_examples_to_generate = 16
# We will reuse this seed overtime (so it's easier)
# to visualize progress in the animated GIF)
seed = tf.random.normal([num_examples_to_generate, noise_dim])
Explanation: Define the training loop
Next, we define the training loop for training our GAN. Below we set up global variables for training.
End of explanation
# TODO 3
@tf.function
def train_step(images):
    noise = tf.random.normal([BATCH_SIZE, noise_dim])
    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
        generated_images = # TODO: Your code goes here.
        real_output = discriminator(images, training=True)
        fake_output = discriminator(generated_images, training=True)
        gen_loss = generator_loss(fake_output)
        disc_loss = discriminator_loss(real_output, fake_output)
    gradients_of_generator = gen_tape.gradient(
        gen_loss, generator.trainable_variables)
    gradients_of_discriminator = disc_tape.gradient(
        disc_loss, discriminator.trainable_variables)
    generator_optimizer.apply_gradients(
        zip(gradients_of_generator, generator.trainable_variables))
    discriminator_optimizer.apply_gradients(
        zip(gradients_of_discriminator, discriminator.trainable_variables))
Explanation: The training loop begins with generator receiving a random seed as input. That seed is used to produce an image. The discriminator is then used to classify real images (drawn from the training set) and fakes images (produced by the generator). The loss is calculated for each of these models, and the gradients are used to update the generator and discriminator.
Exercise.
Complete the code below to define the training loop for our GAN. Notice the use of tf.function below. This annotation causes the function train_step to be "compiled". The train_step function takes as input a batch of images. In the rest of the function,
- generated_images is created using the generator function with noise as input
- apply the discriminator model to the images and generated_images to create the real_output and fake_output (resp.)
- define the gen_loss and disc_loss using the methods you defined above.
- compute the gradients of the generator and the discriminator using gen_tape and disc_tape (resp.)
Lastly, we use the .apply_gradients method to make a gradient step for the generator_optimizer and discriminator_optimizer
End of explanation
def train(dataset, epochs):
    for epoch in range(epochs):
        start = time.time()
        for image_batch in dataset:
            train_step(image_batch)
        # Produce images for the GIF as we go
        display.clear_output(wait=True)
        generate_and_save_images(generator,
                                 epoch + 1,
                                 seed)
        # Save the model every 15 epochs
        if (epoch + 1) % 15 == 0:
            checkpoint.save(file_prefix=checkpoint_prefix)
        print ('Time for epoch {} is {} sec'.format(
            epoch + 1, time.time()-start))
    # Generate after the final epoch
    display.clear_output(wait=True)
    generate_and_save_images(generator,
                             epochs,
                             seed)
Explanation: We use the train_step function above to define training of our GAN. Note here, the train function takes as argument the tf.data dataset and the number of epochs for training.
End of explanation
def generate_and_save_images(model, epoch, test_input):
    # Notice `training` is set to False.
    # This is so all layers run in inference mode (batchnorm).
    predictions = model(test_input, training=False)
    fig = plt.figure(figsize=(4,4))
    for i in range(predictions.shape[0]):
            plt.subplot(4, 4, i+1)
            plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5,
                       cmap='gray')
            plt.axis('off')
    plt.savefig('./gan_images/image_at_epoch_{:04d}.png'.format(epoch))
    plt.show()
Explanation: Generate and save images.
We'll use a small helper function to generate images and save them.
End of explanation
# TODO 4
# TODO: Your code goes here.
Explanation: Train the model
Call the train() method defined above to train the generator and discriminator simultaneously. Note, training GANs can be tricky. It's important that the generator and discriminator do not overpower each other (e.g., that they train at a similar rate).
At the beginning of the training, the generated images look like random noise. As training progresses, the generated digits will look increasingly real. After about 50 epochs, they resemble MNIST digits. This may take about one ot two minutes / epoch.
End of explanation
checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
Explanation: Restore the latest checkpoint.
End of explanation
# Display a single image using the epoch number
def display_image(epoch_no):
    return PIL.Image.open('./gan_images/image_at_epoch_{:04d}.png'.format(epoch_no))
display_image(EPOCHS)
Explanation: Create a GIF
Lastly, we'll create a gif that shows the progression of our produced images through training.
End of explanation
anim_file = 'dcgan.gif'
with imageio.get_writer(anim_file, mode='I') as writer:
    filenames = glob.glob('./gan_images/image*.png')
    filenames = sorted(filenames)
    last = -1
    for i,filename in enumerate(filenames):
        frame = 2*(i**0.5)
        if round(frame) > round(last):
            last = frame
        else:
            continue
        image = imageio.imread(filename)
        writer.append_data(image)
    image = imageio.imread(filename)
    writer.append_data(image)
import IPython
if IPython.version_info > (6,2,0,''):
    display.Image(filename=anim_file)
Explanation: Use imageio to create an animated gif using the images saved during training.
End of explanation
<END_TASK>