Note

Click here to download the full example code

# DCGAN Tutorial¶

**Author**: Nathan Inkawhich

## Introduction¶

This tutorial will give an introduction to DCGANs through an example. We will train a generative adversarial network (GAN) to generate new celebrities after showing it pictures of many real celebrities. Most of the code here is from the dcgan implementation in pytorch/examples, and this document will give a thorough explanation of the implementation and shed light on how and why this model works. But don’t worry, no prior knowledge of GANs is required, but it may require a first-timer to spend some time reasoning about what is actually happening under the hood. Also, for the sake of time it will help to have a GPU, or two. Lets start from the beginning.

## Generative Adversarial Networks¶

### What is a GAN?¶

GANs are a framework for teaching a DL model to capture the training
data’s distribution so we can generate new data from that same
distribution. GANs were invented by Ian Goodfellow in 2014 and first
described in the paper Generative Adversarial
Nets.
They are made of two distinct models, a *generator* and a
*discriminator*. The job of the generator is to spawn ‘fake’ images that
look like the training images. The job of the discriminator is to look
at an image and output whether or not it is a real training image or a
fake image from the generator. During training, the generator is
constantly trying to outsmart the discriminator by generating better and
better fakes, while the discriminator is working to become a better
detective and correctly classify the real and fake images. The
equilibrium of this game is when the generator is generating perfect
fakes that look as if they came directly from the training data, and the
discriminator is left to always guess at 50% confidence that the
generator output is real or fake.

Now, lets define some notation to be used throughout tutorial starting with the discriminator. Let \(x\) be data representing an image. \(D(x)\) is the discriminator network which outputs the (scalar) probability that \(x\) came from training data rather than the generator. Here, since we are dealing with images the input to \(D(x)\) is an image of HWC size 3x64x64. Intuitively, \(D(x)\) should be HIGH when \(x\) comes from training data and LOW when \(x\) comes from the generator. \(D(x)\) can also be thought of as a traditional binary classifier.

For the generator’s notation, let \(z\) be a latent space vector sampled from a standard normal distribution. \(G(z)\) represents the generator function which maps the latent vector \(z\) to data-space. The goal of \(G\) is to estimate the distribution that the training data comes from (\(p_{data}\)) so it can generate fake samples from that estimated distribution (\(p_g\)).

So, \(D(G(z))\) is the probability (scalar) that the output of the generator \(G\) is a real image. As described in Goodfellow’s paper, \(D\) and \(G\) play a minimax game in which \(D\) tries to maximize the probability it correctly classifies reals and fakes (\(logD(x)\)), and \(G\) tries to minimize the probability that \(D\) will predict its outputs are fake (\(log(1-D(G(x)))\)). From the paper, the GAN loss function is

In theory, the solution to this minimax game is where \(p_g = p_{data}\), and the discriminator guesses randomly if the inputs are real or fake. However, the convergence theory of GANs is still being actively researched and in reality models do not always train to this point.

### What is a DCGAN?¶

A DCGAN is a direct extension of the GAN described above, except that it explicitly uses convolutional and convolutional-transpose layers in the discriminator and generator, respectively. It was first described by Radford et. al. in the paper Unsupervised Representation Learning With Deep Convolutional Generative Adversarial Networks. The discriminator is made up of strided convolution layers, batch norm layers, and LeakyReLU activations. The input is a 3x64x64 input image and the output is a scalar probability that the input is from the real data distribution. The generator is comprised of convolutional-transpose layers, batch norm layers, and ReLU activations. The input is a latent vector, \(z\), that is drawn from a standard normal distribution and the output is a 3x64x64 RGB image. The strided conv-transpose layers allow the latent vector to be transformed into a volume with the same shape as an image. In the paper, the authors also give some tips about how to setup the optimizers, how to calculate the loss functions, and how to initialize the model weights, all of which will be explained in the coming sections.

```
from __future__ import print_function
#%matplotlib inline
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
# Set random seem for reproducibility
manualSeed = 999
#manualSeed = random.randint(1, 10000) # use if you want new results
print("Random Seed: ", manualSeed)
random.seed(manualSeed)
torch.manual_seed(manualSeed)
```

Out:

```
Random Seed: 999
```

## Inputs¶

Let’s define some inputs for the run:

**dataroot**- the path to the root of the dataset folder. We will talk more about the dataset in the next section**workers**- the number of worker threads for loading the data with the DataLoader**batch_size**- the batch size used in training. The DCGAN paper uses a batch size of 128**image_size**- the spatial size of the images used for training. This implementation defaults to 64x64. If another size is desired, the structures of D and G must be changed. See here for more details**nc**- number of color channels in the input images. For color images this is 3**nz**- length of latent vector**ngf**- relates to the depth of feature maps carried through the generator**ndf**- sets the depth of feature maps propagated through the discriminator**num_epochs**- number of training epochs to run. Training for longer will probably lead to better results but will also take much longer**lr**- learning rate for training. As described in the DCGAN paper, this number should be 0.0002**beta1**- beta1 hyperparameter for Adam optimizers. As described in paper, this number should be 0.5**ngpu**- number of GPUs available. If this is 0, code will run in CPU mode. If this number is greater than 0 it will run on that number of GPUs

```
# Root directory for dataset
dataroot = "data/celeba"
# Number of workers for dataloader
workers = 2
# Batch size during training
batch_size = 128
# Spatial size of training images. All images will be resized to this
# size using a transformer.
image_size = 64
# Number of channels in the training images. For color images this is 3
nc = 3
# Size of z latent vector (i.e. size of generator input)
nz = 100
# Size of feature maps in generator
ngf = 64
# Size of feature maps in discriminator
ndf = 64
# Number of training epochs
num_epochs = 5
# Learning rate for optimizers
lr = 0.0002
# Beta1 hyperparam for Adam optimizers
beta1 = 0.5
# Number of GPUs available. Use 0 for CPU mode.
ngpu = 1
```

## Data¶

In this tutorial we will use the Celeb-A Faces
dataset which can
be downloaded at the linked site, or in Google
Drive.
The dataset will download as a file named *img_align_celeba.zip*. Once
downloaded, create a directory named *celeba* and extract the zip file
into that directory. Then, set the *dataroot* input for this notebook to
the *celeba* directory you just created. The resulting directory
structure should be:

```
/path/to/celeba
-> img_align_celeba
-> 188242.jpg
-> 173822.jpg
-> 284702.jpg
-> 537394.jpg
...
```

This is an important step because we will be using the ImageFolder dataset class, which requires there to be subdirectories in the dataset’s root folder. Now, we can create the dataset, create the dataloader, set the device to run on, and finally visualize some of the training data.

```
# We can use an image folder dataset the way we have it setup.
# Create the dataset
dataset = dset.ImageFolder(root=dataroot,
transform=transforms.Compose([
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
]))
# Create the dataloader
dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,
shuffle=True, num_workers=workers)
# Decide which device we want to run on
device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu")
# Plot some training images
real_batch = next(iter(dataloader))
plt.figure(figsize=(8,8))
plt.axis("off")
plt.title("Training Images")
plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=2, normalize=True).cpu(),(1,2,0)))
```

## Implementation¶

With our input parameters set and the dataset prepared, we can now get into the implementation. We will start with the weigth initialization strategy, then talk about the generator, discriminator, loss functions, and training loop in detail.

### Weight Initialization¶

From the DCGAN paper, the authors specify that all model weights shall
be randomly initialized from a Normal distribution with mean=0,
stdev=0.2. The `weights_init`

function takes an initialized model as
input and reinitializes all convolutional, convolutional-transpose, and
batch normalization layers to meet this criteria. This function is
applied to the models immediately after initialization.

```
# custom weights initialization called on netG and netD
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find('BatchNorm') != -1:
nn.init.normal_(m.weight.data, 1.0, 0.02)
nn.init.constant_(m.bias.data, 0)
```

### Generator¶

The generator, \(G\), is designed to map the latent space vector (\(z\)) to data-space. Since our data are images, converting \(z\) to data-space means ultimately creating a RGB image with the same size as the training images (i.e. 3x64x64). In practice, this is accomplished through a series of strided two dimensional convolutional transpose layers, each paired with a 2d batch norm layer and a relu activation. The output of the generator is fed through a tanh function to return it to the input data range of \([-1,1]\). It is worth noting the existence of the batch norm functions after the conv-transpose layers, as this is a critical contribution of the DCGAN paper. These layers help with the flow of gradients during training. An image of the generator from the DCGAN paper is shown below.

Notice, the how the inputs we set in the input section (*nz*, *ngf*, and
*nc*) influence the generator architecture in code. *nz* is the length
of the z input vector, *ngf* relates to the size of the feature maps
that are propagated through the generator, and *nc* is the number of
channels in the output image (set to 3 for RGB images). Below is the
code for the generator.

```
# Generator Code
class Generator(nn.Module):
def __init__(self, ngpu):
super(Generator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
# input is Z, going into a convolution
nn.ConvTranspose2d( nz, ngf * 8, 4, 1, 0, bias=False),
nn.BatchNorm2d(ngf * 8),
nn.ReLU(True),
# state size. (ngf*8) x 4 x 4
nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 4),
nn.ReLU(True),
# state size. (ngf*4) x 8 x 8
nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 2),
nn.ReLU(True),
# state size. (ngf*2) x 16 x 16
nn.ConvTranspose2d( ngf * 2, ngf, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf),
nn.ReLU(True),
# state size. (ngf) x 32 x 32
nn.ConvTranspose2d( ngf, nc, 4, 2, 1, bias=False),
nn.Tanh()
# state size. (nc) x 64 x 64
)
def forward(self, input):
return self.main(input)
```

Now, we can instantiate the generator and apply the `weights_init`

function. Check out the printed model to see how the generator object is
structured.

```
# Create the generator
netG = Generator(ngpu).to(device)
# Handle multi-gpu if desired
if (device.type == 'cuda') and (ngpu > 1):
netG = nn.DataParallel(netG, list(range(ngpu)))
# Apply the weights_init function to randomly initialize all weights
# to mean=0, stdev=0.2.
netG.apply(weights_init)
# Print the model
print(netG)
```

Out:

```
Generator(
(main): Sequential(
(0): ConvTranspose2d(100, 512, kernel_size=(4, 4), stride=(1, 1), bias=False)
(1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU(inplace)
(3): ConvTranspose2d(512, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(4): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(5): ReLU(inplace)
(6): ConvTranspose2d(256, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(7): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(8): ReLU(inplace)
(9): ConvTranspose2d(128, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(10): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(11): ReLU(inplace)
(12): ConvTranspose2d(64, 3, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(13): Tanh()
)
)
```

### Discriminator¶

As mentioned, the discriminator, \(D\), is a binary classification network that takes an image as input and outputs a scalar probability that the input image is real (as opposed to fake). Here, \(D\) takes a 3x64x64 input image, processes it through a series of Conv2d, BatchNorm2d, and LeakyReLU layers, and outputs the final probability through a Sigmoid activation function. This architecture can be extended with more layers if necessary for the problem, but there is significance to the use of the strided convolution, BatchNorm, and LeakyReLUs. The DCGAN paper mentions it is a good practice to use strided convolution rather than pooling to downsample because it lets the network learn its own pooling function. Also batch norm and leaky relu functions promote healthy gradient flow which is critical for the learning process of both \(G\) and \(D\).

Discriminator Code

```
class Discriminator(nn.Module):
def __init__(self, ngpu):
super(Discriminator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
# input is (nc) x 64 x 64
nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf) x 32 x 32
nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 2),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*2) x 16 x 16
nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 4),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*4) x 8 x 8
nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 8),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*8) x 4 x 4
nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False),
nn.Sigmoid()
)
def forward(self, input):
return self.main(input)
```

Now, as with the generator, we can create the discriminator, apply the
`weights_init`

function, and print the model’s structure.

```
# Create the Discriminator
netD = Discriminator(ngpu).to(device)
# Handle multi-gpu if desired
if (device.type == 'cuda') and (ngpu > 1):
netD = nn.DataParallel(netD, list(range(ngpu)))
# Apply the weights_init function to randomly initialize all weights
# to mean=0, stdev=0.2.
netD.apply(weights_init)
# Print the model
print(netD)
```

Out:

```
Discriminator(
(main): Sequential(
(0): Conv2d(3, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(1): LeakyReLU(negative_slope=0.2, inplace)
(2): Conv2d(64, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(3): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(4): LeakyReLU(negative_slope=0.2, inplace)
(5): Conv2d(128, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(6): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(7): LeakyReLU(negative_slope=0.2, inplace)
(8): Conv2d(256, 512, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(9): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(10): LeakyReLU(negative_slope=0.2, inplace)
(11): Conv2d(512, 1, kernel_size=(4, 4), stride=(1, 1), bias=False)
(12): Sigmoid()
)
)
```

### Loss Functions and Optimizers¶

With \(D\) and \(G\) setup, we can specify how they learn through the loss functions and optimizers. We will use the Binary Cross Entropy loss (BCELoss) function which is defined in PyTorch as:

Notice how this function provides the calculation of both log components in the objective function (i.e. \(log(D(x))\) and \(log(1-D(G(z)))\)). We can specify what part of the BCE equation to use with the \(y\) input. This is accomplished in the training loop which is coming up soon, but it is important to understand how we can choose which component we wish to calculate just by changing \(y\) (i.e. GT labels).

Next, we define our real label as 1 and the fake label as 0. These labels will be used when calculating the losses of \(D\) and \(G\), and this is also the convention used in the original GAN paper. Finally, we set up two separate optimizers, one for \(D\) and one for \(G\). As specified in the DCGAN paper, both are Adam optimizers with learning rate 0.0002 and Beta1 = 0.5. For keeping track of the generator’s learning progression, we will generate a fixed batch of latent vectors that are drawn from a Gaussian distribution (i.e. fixed_noise) . In the training loop, we will periodically input this fixed_noise into \(G\), and over the iterations we will see images form out of the noise.

```
# Initialize BCELoss function
criterion = nn.BCELoss()
# Create batch of latent vectors that we will use to visualize
# the progression of the generator
fixed_noise = torch.randn(64, nz, 1, 1, device=device)
# Establish convention for real and fake labels during training
real_label = 1
fake_label = 0
# Setup Adam optimizers for both G and D
optimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999))
optimizerG = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999))
```

### Training¶

Finally, now that we have all of the parts of the GAN framework defined, we can train it. Be mindful that training GANs is somewhat of an art form, as incorrect hyperparameter settings lead to mode collapse with little explanation of what went wrong. Here, we will closely follow Algorithm 1 from Goodfellow’s paper, while abiding by some of the best practices shown in ganhacks. Namely, we will “construct different mini-batches for real and fake” images, and also adjust G’s objective function to maximize \(logD(G(z))\). Training is split up into two main parts. Part 1 updates the Discriminator and Part 2 updates the Generator.

**Part 1 - Train the Discriminator**

Recall, the goal of training the discriminator is to maximize the
probability of correctly classifying a given input as real or fake. In
terms of Goodfellow, we wish to “update the discriminator by ascending
its stochastic gradient”. Practically, we want to maximize
\(log(D(x)) + log(1-D(G(z)))\). Due to the separate mini-batch
suggestion from ganhacks, we will calculate this in two steps. First, we
will construct a batch of real samples from the training set, forward
pass through \(D\), calculate the loss (\(log(D(x))\)), then
calculate the gradients in a backward pass. Secondly, we will construct
a batch of fake samples with the current generator, forward pass this
batch through \(D\), calculate the loss (\(log(1-D(G(z)))\)),
and *accumulate* the gradients with a backward pass. Now, with the
gradients accumulated from both the all-real and all-fake batches, we
call a step of the Discriminator’s optimizer.

**Part 2 - Train the Generator**

As stated in the original paper, we want to train the Generator by
minimizing \(log(1-D(G(z)))\) in an effort to generate better fakes.
As mentioned, this was shown by Goodfellow to not provide sufficient
gradients, especially early in the learning process. As a fix, we
instead wish to maximize \(log(D(G(z)))\). In the code we accomplish
this by: classifying the Generator output from Part 1 with the
Discriminator, computing G’s loss *using real labels as GT*, computing
G’s gradients in a backward pass, and finally updating G’s parameters
with an optimizer step. It may seem counter-intuitive to use the real
labels as GT labels for the loss function, but this allows us to use the
\(log(x)\) part of the BCELoss (rather than the \(log(1-x)\)
part) which is exactly what we want.

Finally, we will do some statistic reporting and at the end of each epoch we will push our fixed_noise batch through the generator to visually track the progress of G’s training. The training statistics reported are:

**Loss_D**- discriminator loss calculated as the sum of losses for the all real and all fake batches (\(log(D(x)) + log(D(G(z)))\)).**Loss_G**- generator loss calculated as \(log(D(G(z)))\)**D(x)**- the average output (across the batch) of the discriminator for the all real batch. This should start close to 1 then theoretically converge to 0.5 when G gets better. Think about why this is.**D(G(z))**- average discriminator outputs for the all fake batch. The first number is before D is updated and the second number is after D is updated. These numbers should start near 0 and converge to 0.5 as G gets better. Think about why this is.

**Note:** This step might take a while, depending on how many epochs you
run and if you removed some data from the dataset.

```
# Training Loop
# Lists to keep track of progress
img_list = []
G_losses = []
D_losses = []
iters = 0
print("Starting Training Loop...")
# For each epoch
for epoch in range(num_epochs):
# For each batch in the dataloader
for i, data in enumerate(dataloader, 0):
############################
# (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))
###########################
## Train with all-real batch
netD.zero_grad()
# Format batch
real_cpu = data[0].to(device)
b_size = real_cpu.size(0)
label = torch.full((b_size,), real_label, device=device)
# Forward pass real batch through D
output = netD(real_cpu).view(-1)
# Calculate loss on all-real batch
errD_real = criterion(output, label)
# Calculate gradients for D in backward pass
errD_real.backward()
D_x = output.mean().item()
## Train with all-fake batch
# Generate batch of latent vectors
noise = torch.randn(b_size, nz, 1, 1, device=device)
# Generate fake image batch with G
fake = netG(noise)
label.fill_(fake_label)
# Classify all fake batch with D
output = netD(fake.detach()).view(-1)
# Calculate D's loss on the all-fake batch
errD_fake = criterion(output, label)
# Calculate the gradients for this batch
errD_fake.backward()
D_G_z1 = output.mean().item()
# Add the gradients from the all-real and all-fake batches
errD = errD_real + errD_fake
# Update D
optimizerD.step()
############################
# (2) Update G network: maximize log(D(G(z)))
###########################
netG.zero_grad()
label.fill_(real_label) # fake labels are real for generator cost
# Since we just updated D, perform another forward pass of all-fake batch through D
output = netD(fake).view(-1)
# Calculate G's loss based on this output
errG = criterion(output, label)
# Calculate gradients for G
errG.backward()
D_G_z2 = output.mean().item()
# Update G
optimizerG.step()
# Output training stats
if i % 50 == 0:
print('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(z)): %.4f / %.4f'
% (epoch, num_epochs, i, len(dataloader),
errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))
# Save Losses for plotting later
G_losses.append(errG.item())
D_losses.append(errD.item())
# Check how the generator is doing by saving G's output on fixed_noise
if (iters % 500 == 0) or ((epoch == num_epochs-1) and (i == len(dataloader)-1)):
with torch.no_grad():
fake = netG(fixed_noise).detach().cpu()
img_list.append(vutils.make_grid(fake, padding=2, normalize=True))
iters += 1
```

Out:

```
Starting Training Loop...
[0/5][0/1583] Loss_D: 1.7410 Loss_G: 4.7765 D(x): 0.5343 D(G(z)): 0.5771 / 0.0136
[0/5][50/1583] Loss_D: 0.2913 Loss_G: 27.3206 D(x): 0.8725 D(G(z)): 0.0000 / 0.0000
[0/5][100/1583] Loss_D: 0.8845 Loss_G: 9.8764 D(x): 0.9949 D(G(z)): 0.4462 / 0.0002
[0/5][150/1583] Loss_D: 0.5701 Loss_G: 3.4445 D(x): 0.7888 D(G(z)): 0.2121 / 0.0498
[0/5][200/1583] Loss_D: 0.5400 Loss_G: 4.5821 D(x): 0.6948 D(G(z)): 0.0424 / 0.0207
[0/5][250/1583] Loss_D: 0.3816 Loss_G: 3.9187 D(x): 0.8350 D(G(z)): 0.1299 / 0.0308
[0/5][300/1583] Loss_D: 0.3790 Loss_G: 3.8341 D(x): 0.7831 D(G(z)): 0.0587 / 0.0357
[0/5][350/1583] Loss_D: 0.4119 Loss_G: 4.7852 D(x): 0.8468 D(G(z)): 0.1699 / 0.0140
[0/5][400/1583] Loss_D: 0.5042 Loss_G: 3.4067 D(x): 0.7722 D(G(z)): 0.1282 / 0.0492
[0/5][450/1583] Loss_D: 0.8759 Loss_G: 8.0989 D(x): 0.9018 D(G(z)): 0.4673 / 0.0010
[0/5][500/1583] Loss_D: 0.6009 Loss_G: 5.8161 D(x): 0.6498 D(G(z)): 0.0129 / 0.0109
[0/5][550/1583] Loss_D: 0.6170 Loss_G: 6.3148 D(x): 0.8777 D(G(z)): 0.3132 / 0.0040
[0/5][600/1583] Loss_D: 0.3710 Loss_G: 4.9920 D(x): 0.8838 D(G(z)): 0.1785 / 0.0133
[0/5][650/1583] Loss_D: 0.5502 Loss_G: 6.0860 D(x): 0.9364 D(G(z)): 0.3216 / 0.0052
[0/5][700/1583] Loss_D: 0.5880 Loss_G: 5.6250 D(x): 0.8517 D(G(z)): 0.2754 / 0.0073
[0/5][750/1583] Loss_D: 0.7802 Loss_G: 7.1560 D(x): 0.9069 D(G(z)): 0.4222 / 0.0021
[0/5][800/1583] Loss_D: 1.7804 Loss_G: 6.4755 D(x): 0.9575 D(G(z)): 0.6784 / 0.0043
[0/5][850/1583] Loss_D: 0.5965 Loss_G: 4.3894 D(x): 0.8129 D(G(z)): 0.2496 / 0.0203
[0/5][900/1583] Loss_D: 0.5762 Loss_G: 3.7666 D(x): 0.7108 D(G(z)): 0.0888 / 0.0498
[0/5][950/1583] Loss_D: 0.2698 Loss_G: 3.7843 D(x): 0.8852 D(G(z)): 0.1019 / 0.0457
[0/5][1000/1583] Loss_D: 0.3335 Loss_G: 3.4398 D(x): 0.8197 D(G(z)): 0.0899 / 0.0535
[0/5][1050/1583] Loss_D: 0.6549 Loss_G: 4.8846 D(x): 0.8319 D(G(z)): 0.3103 / 0.0167
[0/5][1100/1583] Loss_D: 0.6474 Loss_G: 2.6426 D(x): 0.6460 D(G(z)): 0.0398 / 0.1183
[0/5][1150/1583] Loss_D: 0.4430 Loss_G: 4.1355 D(x): 0.9066 D(G(z)): 0.2417 / 0.0293
[0/5][1200/1583] Loss_D: 0.4854 Loss_G: 4.5648 D(x): 0.8817 D(G(z)): 0.2576 / 0.0166
[0/5][1250/1583] Loss_D: 0.5112 Loss_G: 3.6469 D(x): 0.7830 D(G(z)): 0.1448 / 0.0538
[0/5][1300/1583] Loss_D: 0.5136 Loss_G: 4.5103 D(x): 0.8658 D(G(z)): 0.2523 / 0.0167
[0/5][1350/1583] Loss_D: 0.5353 Loss_G: 3.3245 D(x): 0.6684 D(G(z)): 0.0234 / 0.0628
[0/5][1400/1583] Loss_D: 1.1608 Loss_G: 6.4351 D(x): 0.9756 D(G(z)): 0.6228 / 0.0053
[0/5][1450/1583] Loss_D: 2.1031 Loss_G: 10.9874 D(x): 0.9793 D(G(z)): 0.7813 / 0.0000
[0/5][1500/1583] Loss_D: 0.5954 Loss_G: 5.4419 D(x): 0.8889 D(G(z)): 0.3111 / 0.0085
[0/5][1550/1583] Loss_D: 0.2545 Loss_G: 3.9333 D(x): 0.8790 D(G(z)): 0.0967 / 0.0324
[1/5][0/1583] Loss_D: 0.5108 Loss_G: 3.5201 D(x): 0.8271 D(G(z)): 0.2249 / 0.0452
[1/5][50/1583] Loss_D: 0.3057 Loss_G: 3.6399 D(x): 0.8934 D(G(z)): 0.1534 / 0.0407
[1/5][100/1583] Loss_D: 1.1070 Loss_G: 6.2737 D(x): 0.9349 D(G(z)): 0.5634 / 0.0044
[1/5][150/1583] Loss_D: 0.5543 Loss_G: 2.5026 D(x): 0.6763 D(G(z)): 0.0665 / 0.1266
[1/5][200/1583] Loss_D: 1.9784 Loss_G: 5.4232 D(x): 0.9161 D(G(z)): 0.7818 / 0.0087
[1/5][250/1583] Loss_D: 0.5625 Loss_G: 4.2356 D(x): 0.8337 D(G(z)): 0.2673 / 0.0216
[1/5][300/1583] Loss_D: 0.4083 Loss_G: 3.7031 D(x): 0.8667 D(G(z)): 0.2076 / 0.0367
[1/5][350/1583] Loss_D: 1.6883 Loss_G: 0.7481 D(x): 0.2591 D(G(z)): 0.0084 / 0.5357
[1/5][400/1583] Loss_D: 0.6552 Loss_G: 5.6395 D(x): 0.9327 D(G(z)): 0.4013 / 0.0064
[1/5][450/1583] Loss_D: 0.5777 Loss_G: 3.9755 D(x): 0.8364 D(G(z)): 0.2666 / 0.0299
[1/5][500/1583] Loss_D: 0.4864 Loss_G: 4.3763 D(x): 0.8989 D(G(z)): 0.2827 / 0.0200
[1/5][550/1583] Loss_D: 0.4686 Loss_G: 4.2680 D(x): 0.9202 D(G(z)): 0.2854 / 0.0237
[1/5][600/1583] Loss_D: 0.6885 Loss_G: 5.2839 D(x): 0.8897 D(G(z)): 0.3894 / 0.0074
[1/5][650/1583] Loss_D: 0.7226 Loss_G: 2.4855 D(x): 0.6273 D(G(z)): 0.0984 / 0.1264
[1/5][700/1583] Loss_D: 0.3968 Loss_G: 3.0834 D(x): 0.8601 D(G(z)): 0.1861 / 0.0674
[1/5][750/1583] Loss_D: 0.6522 Loss_G: 5.0874 D(x): 0.9148 D(G(z)): 0.3827 / 0.0098
[1/5][800/1583] Loss_D: 0.4794 Loss_G: 2.6374 D(x): 0.7576 D(G(z)): 0.1231 / 0.0978
[1/5][850/1583] Loss_D: 0.6545 Loss_G: 2.8344 D(x): 0.7640 D(G(z)): 0.2659 / 0.0808
[1/5][900/1583] Loss_D: 0.3130 Loss_G: 3.8748 D(x): 0.8662 D(G(z)): 0.1308 / 0.0325
[1/5][950/1583] Loss_D: 0.3503 Loss_G: 3.0790 D(x): 0.7772 D(G(z)): 0.0619 / 0.0673
[1/5][1000/1583] Loss_D: 0.4747 Loss_G: 3.2276 D(x): 0.8131 D(G(z)): 0.1844 / 0.0598
[1/5][1050/1583] Loss_D: 0.8616 Loss_G: 1.8546 D(x): 0.5055 D(G(z)): 0.0403 / 0.2027
[1/5][1100/1583] Loss_D: 0.6170 Loss_G: 1.8726 D(x): 0.6447 D(G(z)): 0.0984 / 0.1941
[1/5][1150/1583] Loss_D: 1.1665 Loss_G: 4.9900 D(x): 0.8776 D(G(z)): 0.5664 / 0.0119
[1/5][1200/1583] Loss_D: 0.8937 Loss_G: 1.1257 D(x): 0.5100 D(G(z)): 0.0571 / 0.3945
[1/5][1250/1583] Loss_D: 0.4353 Loss_G: 2.3903 D(x): 0.7685 D(G(z)): 0.1249 / 0.1240
[1/5][1300/1583] Loss_D: 2.6448 Loss_G: 7.7538 D(x): 0.9891 D(G(z)): 0.8753 / 0.0015
[1/5][1350/1583] Loss_D: 0.5649 Loss_G: 2.4311 D(x): 0.8353 D(G(z)): 0.2800 / 0.1191
[1/5][1400/1583] Loss_D: 0.6808 Loss_G: 4.1931 D(x): 0.9287 D(G(z)): 0.4104 / 0.0219
[1/5][1450/1583] Loss_D: 0.3884 Loss_G: 2.7732 D(x): 0.8462 D(G(z)): 0.1751 / 0.0863
[1/5][1500/1583] Loss_D: 0.5661 Loss_G: 2.9044 D(x): 0.8751 D(G(z)): 0.3154 / 0.0750
[1/5][1550/1583] Loss_D: 0.8663 Loss_G: 1.4155 D(x): 0.5244 D(G(z)): 0.0865 / 0.3098
[2/5][0/1583] Loss_D: 0.5749 Loss_G: 2.2547 D(x): 0.6787 D(G(z)): 0.1128 / 0.1372
[2/5][50/1583] Loss_D: 0.6050 Loss_G: 1.9154 D(x): 0.6524 D(G(z)): 0.1070 / 0.1933
[2/5][100/1583] Loss_D: 0.5706 Loss_G: 2.2819 D(x): 0.6681 D(G(z)): 0.1022 / 0.1339
[2/5][150/1583] Loss_D: 0.5914 Loss_G: 2.2584 D(x): 0.7500 D(G(z)): 0.2290 / 0.1299
[2/5][200/1583] Loss_D: 0.4844 Loss_G: 2.5862 D(x): 0.7887 D(G(z)): 0.1900 / 0.0959
[2/5][250/1583] Loss_D: 0.8295 Loss_G: 4.0203 D(x): 0.9462 D(G(z)): 0.4882 / 0.0319
[2/5][300/1583] Loss_D: 1.6811 Loss_G: 5.1996 D(x): 0.9465 D(G(z)): 0.7339 / 0.0092
[2/5][350/1583] Loss_D: 0.6444 Loss_G: 1.8984 D(x): 0.5891 D(G(z)): 0.0342 / 0.1950
[2/5][400/1583] Loss_D: 0.7207 Loss_G: 2.6740 D(x): 0.6931 D(G(z)): 0.2387 / 0.0999
[2/5][450/1583] Loss_D: 0.2633 Loss_G: 3.3940 D(x): 0.8929 D(G(z)): 0.1270 / 0.0444
[2/5][500/1583] Loss_D: 1.0093 Loss_G: 1.3814 D(x): 0.4286 D(G(z)): 0.0188 / 0.2953
[2/5][550/1583] Loss_D: 0.8844 Loss_G: 4.2517 D(x): 0.9008 D(G(z)): 0.4748 / 0.0233
[2/5][600/1583] Loss_D: 0.9445 Loss_G: 4.1339 D(x): 0.9398 D(G(z)): 0.5296 / 0.0269
[2/5][650/1583] Loss_D: 0.3873 Loss_G: 3.0572 D(x): 0.8443 D(G(z)): 0.1756 / 0.0613
[2/5][700/1583] Loss_D: 0.6943 Loss_G: 1.8587 D(x): 0.6160 D(G(z)): 0.1068 / 0.2029
[2/5][750/1583] Loss_D: 0.7173 Loss_G: 1.5541 D(x): 0.6683 D(G(z)): 0.1923 / 0.2485
[2/5][800/1583] Loss_D: 0.5043 Loss_G: 2.6189 D(x): 0.8787 D(G(z)): 0.2744 / 0.0974
[2/5][850/1583] Loss_D: 1.1842 Loss_G: 4.5929 D(x): 0.9170 D(G(z)): 0.6181 / 0.0178
[2/5][900/1583] Loss_D: 0.7059 Loss_G: 3.0826 D(x): 0.7977 D(G(z)): 0.3267 / 0.0669
[2/5][950/1583] Loss_D: 0.5175 Loss_G: 3.4089 D(x): 0.8466 D(G(z)): 0.2681 / 0.0436
[2/5][1000/1583] Loss_D: 0.5258 Loss_G: 2.9226 D(x): 0.8367 D(G(z)): 0.2661 / 0.0669
[2/5][1050/1583] Loss_D: 0.4636 Loss_G: 2.6317 D(x): 0.7717 D(G(z)): 0.1589 / 0.0924
[2/5][1100/1583] Loss_D: 0.5930 Loss_G: 3.1417 D(x): 0.7946 D(G(z)): 0.2671 / 0.0568
[2/5][1150/1583] Loss_D: 0.6186 Loss_G: 2.5936 D(x): 0.7611 D(G(z)): 0.2533 / 0.0961
[2/5][1200/1583] Loss_D: 0.5942 Loss_G: 1.8950 D(x): 0.6548 D(G(z)): 0.0892 / 0.1873
[2/5][1250/1583] Loss_D: 0.5892 Loss_G: 2.8770 D(x): 0.8327 D(G(z)): 0.2989 / 0.0745
[2/5][1300/1583] Loss_D: 0.5566 Loss_G: 3.3825 D(x): 0.8488 D(G(z)): 0.2901 / 0.0457
[2/5][1350/1583] Loss_D: 0.8161 Loss_G: 1.5362 D(x): 0.5539 D(G(z)): 0.1256 / 0.2658
[2/5][1400/1583] Loss_D: 0.6491 Loss_G: 1.6616 D(x): 0.6689 D(G(z)): 0.1703 / 0.2275
[2/5][1450/1583] Loss_D: 0.9300 Loss_G: 2.3294 D(x): 0.7757 D(G(z)): 0.4290 / 0.1281
[2/5][1500/1583] Loss_D: 0.7280 Loss_G: 1.5553 D(x): 0.5797 D(G(z)): 0.0944 / 0.2625
[2/5][1550/1583] Loss_D: 0.7519 Loss_G: 2.7140 D(x): 0.8478 D(G(z)): 0.4020 / 0.0825
[3/5][0/1583] Loss_D: 0.8249 Loss_G: 1.1754 D(x): 0.5313 D(G(z)): 0.1000 / 0.3521
[3/5][50/1583] Loss_D: 2.4646 Loss_G: 0.4075 D(x): 0.1329 D(G(z)): 0.0116 / 0.7011
[3/5][100/1583] Loss_D: 0.9017 Loss_G: 1.6233 D(x): 0.5030 D(G(z)): 0.0609 / 0.2511
[3/5][150/1583] Loss_D: 0.5100 Loss_G: 2.3427 D(x): 0.8676 D(G(z)): 0.2805 / 0.1235
[3/5][200/1583] Loss_D: 0.6214 Loss_G: 2.6225 D(x): 0.7143 D(G(z)): 0.1995 / 0.1000
[3/5][250/1583] Loss_D: 0.8840 Loss_G: 1.4296 D(x): 0.5731 D(G(z)): 0.1937 / 0.2941
[3/5][300/1583] Loss_D: 0.4727 Loss_G: 2.4644 D(x): 0.7363 D(G(z)): 0.1237 / 0.1093
[3/5][350/1583] Loss_D: 0.4415 Loss_G: 2.6914 D(x): 0.8104 D(G(z)): 0.1749 / 0.0882
[3/5][400/1583] Loss_D: 0.6242 Loss_G: 2.3871 D(x): 0.7782 D(G(z)): 0.2732 / 0.1174
[3/5][450/1583] Loss_D: 0.7875 Loss_G: 1.0737 D(x): 0.5876 D(G(z)): 0.1376 / 0.3983
[3/5][500/1583] Loss_D: 0.6895 Loss_G: 4.2050 D(x): 0.9055 D(G(z)): 0.4053 / 0.0232
[3/5][550/1583] Loss_D: 0.7154 Loss_G: 3.5479 D(x): 0.8938 D(G(z)): 0.4080 / 0.0397
[3/5][600/1583] Loss_D: 0.5721 Loss_G: 2.4897 D(x): 0.7685 D(G(z)): 0.2291 / 0.1122
[3/5][650/1583] Loss_D: 0.4995 Loss_G: 2.9295 D(x): 0.8486 D(G(z)): 0.2567 / 0.0719
[3/5][700/1583] Loss_D: 0.8384 Loss_G: 4.0192 D(x): 0.8932 D(G(z)): 0.4601 / 0.0301
[3/5][750/1583] Loss_D: 0.9900 Loss_G: 3.3760 D(x): 0.8385 D(G(z)): 0.4975 / 0.0522
[3/5][800/1583] Loss_D: 0.5181 Loss_G: 2.4808 D(x): 0.7737 D(G(z)): 0.2030 / 0.1052
[3/5][850/1583] Loss_D: 0.6474 Loss_G: 2.1492 D(x): 0.6359 D(G(z)): 0.0849 / 0.1631
[3/5][900/1583] Loss_D: 0.7423 Loss_G: 1.1979 D(x): 0.6364 D(G(z)): 0.1889 / 0.3481
[3/5][950/1583] Loss_D: 0.8323 Loss_G: 3.9171 D(x): 0.9328 D(G(z)): 0.4896 / 0.0269
[3/5][1000/1583] Loss_D: 0.8037 Loss_G: 3.8684 D(x): 0.8782 D(G(z)): 0.4485 / 0.0283
[3/5][1050/1583] Loss_D: 0.6125 Loss_G: 2.8821 D(x): 0.8151 D(G(z)): 0.2900 / 0.0742
[3/5][1100/1583] Loss_D: 0.6844 Loss_G: 3.0779 D(x): 0.8665 D(G(z)): 0.3769 / 0.0629
[3/5][1150/1583] Loss_D: 0.6337 Loss_G: 2.0837 D(x): 0.7457 D(G(z)): 0.2444 / 0.1547
[3/5][1200/1583] Loss_D: 0.4530 Loss_G: 3.3453 D(x): 0.8677 D(G(z)): 0.2439 / 0.0488
[3/5][1250/1583] Loss_D: 0.6742 Loss_G: 2.3392 D(x): 0.7278 D(G(z)): 0.2462 / 0.1187
[3/5][1300/1583] Loss_D: 0.5555 Loss_G: 2.5805 D(x): 0.8496 D(G(z)): 0.2909 / 0.0939
[3/5][1350/1583] Loss_D: 0.7483 Loss_G: 1.1854 D(x): 0.5529 D(G(z)): 0.0760 / 0.3568
[3/5][1400/1583] Loss_D: 0.7197 Loss_G: 3.5704 D(x): 0.8668 D(G(z)): 0.3922 / 0.0383
[3/5][1450/1583] Loss_D: 2.1201 Loss_G: 0.1672 D(x): 0.1653 D(G(z)): 0.0235 / 0.8740
[3/5][1500/1583] Loss_D: 0.6452 Loss_G: 2.9699 D(x): 0.7924 D(G(z)): 0.3005 / 0.0683
[3/5][1550/1583] Loss_D: 0.6481 Loss_G: 3.2820 D(x): 0.8417 D(G(z)): 0.3400 / 0.0502
[4/5][0/1583] Loss_D: 1.1235 Loss_G: 0.6507 D(x): 0.4275 D(G(z)): 0.1208 / 0.5714
[4/5][50/1583] Loss_D: 0.4938 Loss_G: 2.6457 D(x): 0.8007 D(G(z)): 0.2026 / 0.0934
[4/5][100/1583] Loss_D: 0.5935 Loss_G: 2.3206 D(x): 0.7578 D(G(z)): 0.2163 / 0.1364
[4/5][150/1583] Loss_D: 0.7663 Loss_G: 3.0891 D(x): 0.8652 D(G(z)): 0.4193 / 0.0650
[4/5][200/1583] Loss_D: 1.0856 Loss_G: 4.7791 D(x): 0.9557 D(G(z)): 0.5977 / 0.0139
[4/5][250/1583] Loss_D: 0.7172 Loss_G: 2.0143 D(x): 0.6798 D(G(z)): 0.2200 / 0.1613
[4/5][300/1583] Loss_D: 0.7093 Loss_G: 2.0855 D(x): 0.6448 D(G(z)): 0.1734 / 0.1635
[4/5][350/1583] Loss_D: 0.4988 Loss_G: 2.5742 D(x): 0.7529 D(G(z)): 0.1561 / 0.0986
[4/5][400/1583] Loss_D: 0.6381 Loss_G: 1.7872 D(x): 0.6062 D(G(z)): 0.0666 / 0.2141
[4/5][450/1583] Loss_D: 0.6353 Loss_G: 2.5315 D(x): 0.7867 D(G(z)): 0.2912 / 0.1010
[4/5][500/1583] Loss_D: 0.6637 Loss_G: 3.5648 D(x): 0.9442 D(G(z)): 0.4189 / 0.0361
[4/5][550/1583] Loss_D: 0.5461 Loss_G: 2.4011 D(x): 0.7328 D(G(z)): 0.1639 / 0.1121
[4/5][600/1583] Loss_D: 1.1140 Loss_G: 1.3266 D(x): 0.4037 D(G(z)): 0.0384 / 0.3262
[4/5][650/1583] Loss_D: 1.5140 Loss_G: 4.7118 D(x): 0.8491 D(G(z)): 0.6626 / 0.0153
[4/5][700/1583] Loss_D: 0.6046 Loss_G: 2.6768 D(x): 0.8754 D(G(z)): 0.3322 / 0.0887
[4/5][750/1583] Loss_D: 0.5414 Loss_G: 2.0473 D(x): 0.7036 D(G(z)): 0.1187 / 0.1639
[4/5][800/1583] Loss_D: 0.5834 Loss_G: 2.5215 D(x): 0.8196 D(G(z)): 0.2806 / 0.1031
[4/5][850/1583] Loss_D: 0.8337 Loss_G: 1.7287 D(x): 0.6168 D(G(z)): 0.2169 / 0.2183
[4/5][900/1583] Loss_D: 0.6726 Loss_G: 1.9821 D(x): 0.6773 D(G(z)): 0.1969 / 0.1706
[4/5][950/1583] Loss_D: 0.8011 Loss_G: 2.2303 D(x): 0.5480 D(G(z)): 0.0819 / 0.1472
[4/5][1000/1583] Loss_D: 0.5181 Loss_G: 2.4381 D(x): 0.8540 D(G(z)): 0.2690 / 0.1082
[4/5][1050/1583] Loss_D: 2.6980 Loss_G: 0.1360 D(x): 0.1065 D(G(z)): 0.0187 / 0.8866
[4/5][1100/1583] Loss_D: 0.6896 Loss_G: 3.2757 D(x): 0.8760 D(G(z)): 0.3931 / 0.0474
[4/5][1150/1583] Loss_D: 0.5826 Loss_G: 2.2118 D(x): 0.7190 D(G(z)): 0.1875 / 0.1417
[4/5][1200/1583] Loss_D: 0.7822 Loss_G: 3.6914 D(x): 0.8733 D(G(z)): 0.4308 / 0.0338
[4/5][1250/1583] Loss_D: 1.4110 Loss_G: 0.3719 D(x): 0.3172 D(G(z)): 0.0488 / 0.7127
[4/5][1300/1583] Loss_D: 0.6790 Loss_G: 1.2476 D(x): 0.5989 D(G(z)): 0.0965 / 0.3366
[4/5][1350/1583] Loss_D: 0.8312 Loss_G: 4.2156 D(x): 0.9318 D(G(z)): 0.4816 / 0.0213
[4/5][1400/1583] Loss_D: 1.5377 Loss_G: 0.3751 D(x): 0.2823 D(G(z)): 0.0394 / 0.7148
[4/5][1450/1583] Loss_D: 0.6127 Loss_G: 3.6128 D(x): 0.9081 D(G(z)): 0.3650 / 0.0354
[4/5][1500/1583] Loss_D: 0.6328 Loss_G: 1.9700 D(x): 0.6545 D(G(z)): 0.1332 / 0.1859
[4/5][1550/1583] Loss_D: 1.2825 Loss_G: 0.8622 D(x): 0.3590 D(G(z)): 0.0437 / 0.4739
```

## Results¶

Finally, lets check out how we did. Here, we will look at three different results. First, we will see how D and G’s losses changed during training. Second, we will visualize G’s output on the fixed_noise batch for every epoch. And third, we will look at a batch of real data next to a batch of fake data from G.

**Loss versus training iteration**

Below is a plot of D & G’s losses versus training iterations.

```
plt.figure(figsize=(10,5))
plt.title("Generator and Discriminator Loss During Training")
plt.plot(G_losses,label="G")
plt.plot(D_losses,label="D")
plt.xlabel("iterations")
plt.ylabel("Loss")
plt.legend()
plt.show()
```

**Visualization of G’s progression**

Remember how we saved the generator’s output on the fixed_noise batch after every epoch of training. Now, we can visualize the training progression of G with an animation. Press the play button to start the animation.

```
#%%capture
fig = plt.figure(figsize=(8,8))
plt.axis("off")
ims = [[plt.imshow(np.transpose(i,(1,2,0)), animated=True)] for i in img_list]
ani = animation.ArtistAnimation(fig, ims, interval=1000, repeat_delay=1000, blit=True)
HTML(ani.to_jshtml())
```

**Real Images vs. Fake Images**

Finally, lets take a look at some real images and fake images side by side.

```
# Grab a batch of real images from the dataloader
real_batch = next(iter(dataloader))
# Plot the real images
plt.figure(figsize=(15,15))
plt.subplot(1,2,1)
plt.axis("off")
plt.title("Real Images")
plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=5, normalize=True).cpu(),(1,2,0)))
# Plot the fake images from the last epoch
plt.subplot(1,2,2)
plt.axis("off")
plt.title("Fake Images")
plt.imshow(np.transpose(img_list[-1],(1,2,0)))
plt.show()
```

## Where to Go Next¶

We have reached the end of our journey, but there are several places you could go from here. You could:

- Train for longer to see how good the results get
- Modify this model to take a different dataset and possibly change the size of the images and the model architecture
- Check out some other cool GAN projects here
- Create GANs that generate music

**Total running time of the script:** ( 28 minutes 26.137 seconds)