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 deep learning model to capture the training
data 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 CHW 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(z)))\)). 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.

```
#%matplotlib inline
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
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 seed 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)
torch.use_deterministic_algorithms(True) # Needed for reproducible results
```

```
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 hyperparameter 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 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)))
plt.show()
```

## Implementation¶

With our input parameters set and the dataset prepared, we can now get into the implementation. We will start with the weight 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.02`

. 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, 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.02``.
netG.apply(weights_init)
# Print the model
print(netG)
```

```
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=True)
(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=True)
(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=True)
(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=True)
(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
# like this: ``to mean=0, stdev=0.2``.
netD.apply(weights_init)
# Print the model
print(netD)
```

```
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=True)
(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=True)
(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=True)
(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=True)
(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 the ``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 the 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 \(log(D(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(1 - 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, dtype=torch.float, 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, accumulated (summed) with previous gradients
errD_fake.backward()
D_G_z1 = output.mean().item()
# Compute error of D as sum over the fake and the real 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
```

```
Starting Training Loop...
[0/5][0/1583] Loss_D: 1.4639 Loss_G: 6.9356 D(x): 0.7143 D(G(z)): 0.5877 / 0.0017
[0/5][50/1583] Loss_D: 0.3242 Loss_G: 31.5483 D(x): 0.8383 D(G(z)): 0.0000 / 0.0000
[0/5][100/1583] Loss_D: 0.6255 Loss_G: 4.1696 D(x): 0.7227 D(G(z)): 0.0358 / 0.0356
[0/5][150/1583] Loss_D: 0.2219 Loss_G: 3.3579 D(x): 0.9007 D(G(z)): 0.0666 / 0.0863
[0/5][200/1583] Loss_D: 0.8795 Loss_G: 4.5660 D(x): 0.6613 D(G(z)): 0.2131 / 0.0210
[0/5][250/1583] Loss_D: 0.4980 Loss_G: 3.2480 D(x): 0.7250 D(G(z)): 0.0488 / 0.1019
[0/5][300/1583] Loss_D: 1.6464 Loss_G: 4.2970 D(x): 0.3272 D(G(z)): 0.0047 / 0.0320
[0/5][350/1583] Loss_D: 0.6214 Loss_G: 4.2107 D(x): 0.9090 D(G(z)): 0.3447 / 0.0251
[0/5][400/1583] Loss_D: 0.6713 Loss_G: 4.2897 D(x): 0.9257 D(G(z)): 0.3878 / 0.0294
[0/5][450/1583] Loss_D: 0.5819 Loss_G: 3.9728 D(x): 0.7532 D(G(z)): 0.1509 / 0.0317
[0/5][500/1583] Loss_D: 1.4538 Loss_G: 1.0834 D(x): 0.3934 D(G(z)): 0.1352 / 0.4428
[0/5][550/1583] Loss_D: 0.4030 Loss_G: 4.4588 D(x): 0.8614 D(G(z)): 0.1533 / 0.0207
[0/5][600/1583] Loss_D: 0.6030 Loss_G: 3.2111 D(x): 0.6778 D(G(z)): 0.0695 / 0.0673
[0/5][650/1583] Loss_D: 0.8971 Loss_G: 4.5883 D(x): 0.7796 D(G(z)): 0.3915 / 0.0173
[0/5][700/1583] Loss_D: 0.3551 Loss_G: 5.3014 D(x): 0.8556 D(G(z)): 0.1236 / 0.0085
[0/5][750/1583] Loss_D: 1.1255 Loss_G: 3.2437 D(x): 0.4403 D(G(z)): 0.0122 / 0.0860
[0/5][800/1583] Loss_D: 0.3147 Loss_G: 4.5361 D(x): 0.8490 D(G(z)): 0.1034 / 0.0186
[0/5][850/1583] Loss_D: 0.7247 Loss_G: 2.6568 D(x): 0.6426 D(G(z)): 0.1107 / 0.1354
[0/5][900/1583] Loss_D: 0.2811 Loss_G: 3.4807 D(x): 0.8552 D(G(z)): 0.0830 / 0.0534
[0/5][950/1583] Loss_D: 0.7600 Loss_G: 6.4174 D(x): 0.8989 D(G(z)): 0.3859 / 0.0054
[0/5][1000/1583] Loss_D: 0.3480 Loss_G: 5.2934 D(x): 0.9010 D(G(z)): 0.1750 / 0.0145
[0/5][1050/1583] Loss_D: 0.5616 Loss_G: 5.3993 D(x): 0.7005 D(G(z)): 0.0210 / 0.0139
[0/5][1100/1583] Loss_D: 0.1591 Loss_G: 4.6903 D(x): 0.9135 D(G(z)): 0.0464 / 0.0168
[0/5][1150/1583] Loss_D: 0.3180 Loss_G: 4.7279 D(x): 0.8923 D(G(z)): 0.1549 / 0.0145
[0/5][1200/1583] Loss_D: 0.4964 Loss_G: 4.0195 D(x): 0.8374 D(G(z)): 0.2212 / 0.0322
[0/5][1250/1583] Loss_D: 1.0099 Loss_G: 6.1041 D(x): 0.9504 D(G(z)): 0.5440 / 0.0055
[0/5][1300/1583] Loss_D: 0.4111 Loss_G: 5.3166 D(x): 0.8679 D(G(z)): 0.1921 / 0.0089
[0/5][1350/1583] Loss_D: 1.8342 Loss_G: 1.6638 D(x): 0.2817 D(G(z)): 0.0134 / 0.2739
[0/5][1400/1583] Loss_D: 0.4436 Loss_G: 4.5273 D(x): 0.8271 D(G(z)): 0.1715 / 0.0195
[0/5][1450/1583] Loss_D: 0.9782 Loss_G: 2.6528 D(x): 0.4883 D(G(z)): 0.0166 / 0.1239
[0/5][1500/1583] Loss_D: 0.6928 Loss_G: 3.2443 D(x): 0.6108 D(G(z)): 0.0365 / 0.0691
[0/5][1550/1583] Loss_D: 0.4835 Loss_G: 4.4397 D(x): 0.8843 D(G(z)): 0.2668 / 0.0192
[1/5][0/1583] Loss_D: 0.6268 Loss_G: 4.9622 D(x): 0.9252 D(G(z)): 0.3613 / 0.0135
[1/5][50/1583] Loss_D: 0.7514 Loss_G: 0.7346 D(x): 0.5730 D(G(z)): 0.0373 / 0.5340
[1/5][100/1583] Loss_D: 0.4567 Loss_G: 3.0858 D(x): 0.7565 D(G(z)): 0.1009 / 0.0716
[1/5][150/1583] Loss_D: 0.5032 Loss_G: 3.5198 D(x): 0.7965 D(G(z)): 0.1911 / 0.0456
[1/5][200/1583] Loss_D: 0.5624 Loss_G: 3.2230 D(x): 0.8774 D(G(z)): 0.3011 / 0.0633
[1/5][250/1583] Loss_D: 1.1976 Loss_G: 1.7349 D(x): 0.4448 D(G(z)): 0.0122 / 0.2734
[1/5][300/1583] Loss_D: 0.5653 Loss_G: 4.2695 D(x): 0.8712 D(G(z)): 0.2859 / 0.0234
[1/5][350/1583] Loss_D: 2.1271 Loss_G: 2.1558 D(x): 0.1991 D(G(z)): 0.0065 / 0.1695
[1/5][400/1583] Loss_D: 0.3964 Loss_G: 3.1797 D(x): 0.7650 D(G(z)): 0.0825 / 0.0578
[1/5][450/1583] Loss_D: 0.4872 Loss_G: 4.7998 D(x): 0.9149 D(G(z)): 0.2904 / 0.0139
[1/5][500/1583] Loss_D: 0.3336 Loss_G: 3.4355 D(x): 0.8826 D(G(z)): 0.1566 / 0.0517
[1/5][550/1583] Loss_D: 0.6615 Loss_G: 3.5165 D(x): 0.7637 D(G(z)): 0.2485 / 0.0470
[1/5][600/1583] Loss_D: 0.5524 Loss_G: 2.7687 D(x): 0.6851 D(G(z)): 0.0846 / 0.0946
[1/5][650/1583] Loss_D: 0.5974 Loss_G: 4.2535 D(x): 0.9131 D(G(z)): 0.3298 / 0.0285
[1/5][700/1583] Loss_D: 0.4352 Loss_G: 3.6688 D(x): 0.9428 D(G(z)): 0.2688 / 0.0460
[1/5][750/1583] Loss_D: 0.3833 Loss_G: 2.9862 D(x): 0.8509 D(G(z)): 0.1604 / 0.0680
[1/5][800/1583] Loss_D: 0.5156 Loss_G: 3.0845 D(x): 0.7028 D(G(z)): 0.0994 / 0.0728
[1/5][850/1583] Loss_D: 1.3500 Loss_G: 8.4715 D(x): 0.9820 D(G(z)): 0.6608 / 0.0004
[1/5][900/1583] Loss_D: 0.7279 Loss_G: 5.5268 D(x): 0.8525 D(G(z)): 0.3799 / 0.0087
[1/5][950/1583] Loss_D: 0.5133 Loss_G: 2.6554 D(x): 0.7431 D(G(z)): 0.1307 / 0.0929
[1/5][1000/1583] Loss_D: 0.5413 Loss_G: 4.2976 D(x): 0.8956 D(G(z)): 0.3027 / 0.0233
[1/5][1050/1583] Loss_D: 0.6781 Loss_G: 1.9833 D(x): 0.6030 D(G(z)): 0.0238 / 0.2025
[1/5][1100/1583] Loss_D: 0.4322 Loss_G: 2.6027 D(x): 0.7542 D(G(z)): 0.0740 / 0.1022
[1/5][1150/1583] Loss_D: 1.1863 Loss_G: 5.5669 D(x): 0.9340 D(G(z)): 0.6007 / 0.0069
[1/5][1200/1583] Loss_D: 0.6455 Loss_G: 4.5968 D(x): 0.9106 D(G(z)): 0.3760 / 0.0180
[1/5][1250/1583] Loss_D: 0.7295 Loss_G: 3.1293 D(x): 0.7430 D(G(z)): 0.2787 / 0.0727
[1/5][1300/1583] Loss_D: 1.0030 Loss_G: 1.7375 D(x): 0.4721 D(G(z)): 0.0533 / 0.2379
[1/5][1350/1583] Loss_D: 1.6538 Loss_G: 5.9430 D(x): 0.9442 D(G(z)): 0.7357 / 0.0052
[1/5][1400/1583] Loss_D: 0.5649 Loss_G: 2.9169 D(x): 0.8183 D(G(z)): 0.2687 / 0.0734
[1/5][1450/1583] Loss_D: 0.4261 Loss_G: 3.0610 D(x): 0.7964 D(G(z)): 0.1375 / 0.0621
[1/5][1500/1583] Loss_D: 0.4946 Loss_G: 3.1410 D(x): 0.8565 D(G(z)): 0.2451 / 0.0738
[1/5][1550/1583] Loss_D: 0.8549 Loss_G: 1.7395 D(x): 0.5435 D(G(z)): 0.0914 / 0.2417
[2/5][0/1583] Loss_D: 0.5623 Loss_G: 2.1095 D(x): 0.6400 D(G(z)): 0.0452 / 0.1684
[2/5][50/1583] Loss_D: 0.5614 Loss_G: 4.2505 D(x): 0.9462 D(G(z)): 0.3607 / 0.0201
[2/5][100/1583] Loss_D: 0.7408 Loss_G: 1.7462 D(x): 0.6195 D(G(z)): 0.1396 / 0.2273
[2/5][150/1583] Loss_D: 0.4944 Loss_G: 2.2602 D(x): 0.7388 D(G(z)): 0.1378 / 0.1415
[2/5][200/1583] Loss_D: 0.6049 Loss_G: 2.6208 D(x): 0.7689 D(G(z)): 0.2524 / 0.0962
[2/5][250/1583] Loss_D: 0.5664 Loss_G: 2.9909 D(x): 0.8120 D(G(z)): 0.2578 / 0.0660
[2/5][300/1583] Loss_D: 0.5038 Loss_G: 3.4062 D(x): 0.8648 D(G(z)): 0.2613 / 0.0484
[2/5][350/1583] Loss_D: 0.5945 Loss_G: 1.9982 D(x): 0.7523 D(G(z)): 0.2242 / 0.1662
[2/5][400/1583] Loss_D: 1.1467 Loss_G: 4.7130 D(x): 0.8820 D(G(z)): 0.5668 / 0.0155
[2/5][450/1583] Loss_D: 0.6520 Loss_G: 3.4336 D(x): 0.9213 D(G(z)): 0.4030 / 0.0441
[2/5][500/1583] Loss_D: 0.8613 Loss_G: 1.0815 D(x): 0.5288 D(G(z)): 0.0760 / 0.3905
[2/5][550/1583] Loss_D: 0.6906 Loss_G: 4.1047 D(x): 0.8655 D(G(z)): 0.3697 / 0.0280
[2/5][600/1583] Loss_D: 0.5654 Loss_G: 1.9830 D(x): 0.6963 D(G(z)): 0.1304 / 0.1729
[2/5][650/1583] Loss_D: 0.6044 Loss_G: 1.8089 D(x): 0.7001 D(G(z)): 0.1727 / 0.2082
[2/5][700/1583] Loss_D: 0.6106 Loss_G: 1.6630 D(x): 0.6461 D(G(z)): 0.0877 / 0.2441
[2/5][750/1583] Loss_D: 1.0203 Loss_G: 1.3345 D(x): 0.5085 D(G(z)): 0.1785 / 0.3240
[2/5][800/1583] Loss_D: 0.5377 Loss_G: 2.5538 D(x): 0.7565 D(G(z)): 0.1961 / 0.1027
[2/5][850/1583] Loss_D: 0.3789 Loss_G: 3.0581 D(x): 0.8850 D(G(z)): 0.2092 / 0.0621
[2/5][900/1583] Loss_D: 1.3570 Loss_G: 4.9757 D(x): 0.9622 D(G(z)): 0.6302 / 0.0141
[2/5][950/1583] Loss_D: 0.6596 Loss_G: 2.4686 D(x): 0.7542 D(G(z)): 0.2721 / 0.1085
[2/5][1000/1583] Loss_D: 0.6875 Loss_G: 1.4414 D(x): 0.6144 D(G(z)): 0.1249 / 0.2787
[2/5][1050/1583] Loss_D: 0.4792 Loss_G: 2.6635 D(x): 0.7570 D(G(z)): 0.1479 / 0.0962
[2/5][1100/1583] Loss_D: 1.0462 Loss_G: 4.0517 D(x): 0.8556 D(G(z)): 0.5220 / 0.0298
[2/5][1150/1583] Loss_D: 0.5255 Loss_G: 2.5377 D(x): 0.8195 D(G(z)): 0.2469 / 0.0990
[2/5][1200/1583] Loss_D: 0.4260 Loss_G: 3.4207 D(x): 0.9237 D(G(z)): 0.2649 / 0.0436
[2/5][1250/1583] Loss_D: 0.4721 Loss_G: 2.3755 D(x): 0.7558 D(G(z)): 0.1434 / 0.1175
[2/5][1300/1583] Loss_D: 1.0240 Loss_G: 4.2717 D(x): 0.8719 D(G(z)): 0.5166 / 0.0230
[2/5][1350/1583] Loss_D: 0.5882 Loss_G: 1.7832 D(x): 0.7439 D(G(z)): 0.2153 / 0.2073
[2/5][1400/1583] Loss_D: 0.6932 Loss_G: 3.7904 D(x): 0.9076 D(G(z)): 0.4070 / 0.0330
[2/5][1450/1583] Loss_D: 0.8912 Loss_G: 4.0172 D(x): 0.8996 D(G(z)): 0.4849 / 0.0256
[2/5][1500/1583] Loss_D: 0.7962 Loss_G: 4.5561 D(x): 0.9384 D(G(z)): 0.4720 / 0.0171
[2/5][1550/1583] Loss_D: 0.7970 Loss_G: 4.4968 D(x): 0.9568 D(G(z)): 0.4803 / 0.0177
[3/5][0/1583] Loss_D: 0.6207 Loss_G: 1.9942 D(x): 0.6708 D(G(z)): 0.1338 / 0.1703
[3/5][50/1583] Loss_D: 0.8271 Loss_G: 0.8199 D(x): 0.5310 D(G(z)): 0.0875 / 0.4851
[3/5][100/1583] Loss_D: 0.4647 Loss_G: 2.4834 D(x): 0.7816 D(G(z)): 0.1693 / 0.1163
[3/5][150/1583] Loss_D: 0.4473 Loss_G: 2.5716 D(x): 0.8176 D(G(z)): 0.1905 / 0.1006
[3/5][200/1583] Loss_D: 0.6719 Loss_G: 3.3996 D(x): 0.8535 D(G(z)): 0.3625 / 0.0451
[3/5][250/1583] Loss_D: 0.4477 Loss_G: 2.9992 D(x): 0.8987 D(G(z)): 0.2639 / 0.0669
[3/5][300/1583] Loss_D: 0.8086 Loss_G: 1.4259 D(x): 0.6547 D(G(z)): 0.2408 / 0.2925
[3/5][350/1583] Loss_D: 0.5199 Loss_G: 1.9725 D(x): 0.8318 D(G(z)): 0.2539 / 0.1746
[3/5][400/1583] Loss_D: 0.5976 Loss_G: 1.6428 D(x): 0.6476 D(G(z)): 0.1018 / 0.2381
[3/5][450/1583] Loss_D: 0.6942 Loss_G: 3.5290 D(x): 0.8904 D(G(z)): 0.3982 / 0.0395
[3/5][500/1583] Loss_D: 1.1736 Loss_G: 0.7940 D(x): 0.4196 D(G(z)): 0.0627 / 0.4958
[3/5][550/1583] Loss_D: 0.6200 Loss_G: 2.4844 D(x): 0.8689 D(G(z)): 0.3360 / 0.1066
[3/5][600/1583] Loss_D: 0.9227 Loss_G: 1.6358 D(x): 0.5063 D(G(z)): 0.1036 / 0.2437
[3/5][650/1583] Loss_D: 0.5858 Loss_G: 3.6943 D(x): 0.8388 D(G(z)): 0.3057 / 0.0372
[3/5][700/1583] Loss_D: 0.6033 Loss_G: 2.0149 D(x): 0.7311 D(G(z)): 0.1964 / 0.1781
[3/5][750/1583] Loss_D: 0.5502 Loss_G: 3.1818 D(x): 0.8601 D(G(z)): 0.3002 / 0.0541
[3/5][800/1583] Loss_D: 0.6964 Loss_G: 3.9791 D(x): 0.8740 D(G(z)): 0.3934 / 0.0255
[3/5][850/1583] Loss_D: 1.3287 Loss_G: 1.1903 D(x): 0.3969 D(G(z)): 0.1147 / 0.3856
[3/5][900/1583] Loss_D: 0.6994 Loss_G: 3.3330 D(x): 0.8640 D(G(z)): 0.3838 / 0.0500
[3/5][950/1583] Loss_D: 0.8296 Loss_G: 0.9049 D(x): 0.5234 D(G(z)): 0.0647 / 0.4408
[3/5][1000/1583] Loss_D: 1.0949 Loss_G: 0.7958 D(x): 0.4138 D(G(z)): 0.0365 / 0.4985
[3/5][1050/1583] Loss_D: 0.6095 Loss_G: 2.4836 D(x): 0.7916 D(G(z)): 0.2766 / 0.1107
[3/5][1100/1583] Loss_D: 0.4538 Loss_G: 2.0659 D(x): 0.7611 D(G(z)): 0.1358 / 0.1586
[3/5][1150/1583] Loss_D: 0.6258 Loss_G: 2.2310 D(x): 0.6639 D(G(z)): 0.1423 / 0.1486
[3/5][1200/1583] Loss_D: 0.5801 Loss_G: 1.4977 D(x): 0.6810 D(G(z)): 0.1214 / 0.2645
[3/5][1250/1583] Loss_D: 2.3328 Loss_G: 4.3672 D(x): 0.9818 D(G(z)): 0.8527 / 0.0235
[3/5][1300/1583] Loss_D: 0.5145 Loss_G: 2.7098 D(x): 0.8002 D(G(z)): 0.2147 / 0.0871
[3/5][1350/1583] Loss_D: 0.7088 Loss_G: 0.9405 D(x): 0.6495 D(G(z)): 0.1748 / 0.4374
[3/5][1400/1583] Loss_D: 0.9545 Loss_G: 1.3225 D(x): 0.5137 D(G(z)): 0.1441 / 0.3294
[3/5][1450/1583] Loss_D: 0.5780 Loss_G: 1.8844 D(x): 0.7241 D(G(z)): 0.1891 / 0.1926
[3/5][1500/1583] Loss_D: 0.5709 Loss_G: 1.8434 D(x): 0.7404 D(G(z)): 0.1949 / 0.2120
[3/5][1550/1583] Loss_D: 0.5434 Loss_G: 2.0119 D(x): 0.7713 D(G(z)): 0.2165 / 0.1718
[4/5][0/1583] Loss_D: 0.4163 Loss_G: 2.6372 D(x): 0.8265 D(G(z)): 0.1795 / 0.0943
[4/5][50/1583] Loss_D: 0.6529 Loss_G: 2.0663 D(x): 0.7036 D(G(z)): 0.2107 / 0.1570
[4/5][100/1583] Loss_D: 0.7297 Loss_G: 1.5304 D(x): 0.5676 D(G(z)): 0.0706 / 0.2603
[4/5][150/1583] Loss_D: 0.6044 Loss_G: 1.5723 D(x): 0.6480 D(G(z)): 0.0917 / 0.2653
[4/5][200/1583] Loss_D: 0.8838 Loss_G: 3.6003 D(x): 0.8782 D(G(z)): 0.4936 / 0.0406
[4/5][250/1583] Loss_D: 0.6898 Loss_G: 3.9428 D(x): 0.8996 D(G(z)): 0.3995 / 0.0281
[4/5][300/1583] Loss_D: 0.6976 Loss_G: 1.6595 D(x): 0.6783 D(G(z)): 0.2150 / 0.2308
[4/5][350/1583] Loss_D: 1.3657 Loss_G: 5.0456 D(x): 0.9590 D(G(z)): 0.6777 / 0.0097
[4/5][400/1583] Loss_D: 0.6273 Loss_G: 1.8805 D(x): 0.6428 D(G(z)): 0.1129 / 0.1901
[4/5][450/1583] Loss_D: 0.5668 Loss_G: 2.2586 D(x): 0.7622 D(G(z)): 0.2226 / 0.1269
[4/5][500/1583] Loss_D: 0.5272 Loss_G: 2.0144 D(x): 0.7180 D(G(z)): 0.1372 / 0.1623
[4/5][550/1583] Loss_D: 2.2434 Loss_G: 5.3635 D(x): 0.9622 D(G(z)): 0.8132 / 0.0124
[4/5][600/1583] Loss_D: 1.2922 Loss_G: 5.5550 D(x): 0.9562 D(G(z)): 0.6563 / 0.0061
[4/5][650/1583] Loss_D: 0.5544 Loss_G: 2.2016 D(x): 0.8119 D(G(z)): 0.2580 / 0.1429
[4/5][700/1583] Loss_D: 0.4944 Loss_G: 1.9504 D(x): 0.7448 D(G(z)): 0.1440 / 0.1755
[4/5][750/1583] Loss_D: 0.4139 Loss_G: 2.3911 D(x): 0.8139 D(G(z)): 0.1624 / 0.1218
[4/5][800/1583] Loss_D: 0.7332 Loss_G: 1.7267 D(x): 0.6219 D(G(z)): 0.1537 / 0.2255
[4/5][850/1583] Loss_D: 0.6277 Loss_G: 1.9473 D(x): 0.6935 D(G(z)): 0.1791 / 0.1803
[4/5][900/1583] Loss_D: 0.7917 Loss_G: 3.7302 D(x): 0.9017 D(G(z)): 0.4523 / 0.0328
[4/5][950/1583] Loss_D: 0.5253 Loss_G: 2.1947 D(x): 0.7346 D(G(z)): 0.1590 / 0.1411
[4/5][1000/1583] Loss_D: 1.1477 Loss_G: 4.9436 D(x): 0.9429 D(G(z)): 0.6048 / 0.0121
[4/5][1050/1583] Loss_D: 0.6783 Loss_G: 4.0750 D(x): 0.8798 D(G(z)): 0.3849 / 0.0225
[4/5][1100/1583] Loss_D: 0.6448 Loss_G: 2.5082 D(x): 0.6359 D(G(z)): 0.0836 / 0.1189
[4/5][1150/1583] Loss_D: 0.9304 Loss_G: 0.6922 D(x): 0.4841 D(G(z)): 0.0729 / 0.5382
[4/5][1200/1583] Loss_D: 0.5627 Loss_G: 4.1992 D(x): 0.9206 D(G(z)): 0.3443 / 0.0217
[4/5][1250/1583] Loss_D: 0.7861 Loss_G: 1.5696 D(x): 0.6637 D(G(z)): 0.2357 / 0.2554
[4/5][1300/1583] Loss_D: 0.6603 Loss_G: 4.2306 D(x): 0.9545 D(G(z)): 0.4271 / 0.0212
[4/5][1350/1583] Loss_D: 0.9006 Loss_G: 1.5437 D(x): 0.5667 D(G(z)): 0.1951 / 0.2718
[4/5][1400/1583] Loss_D: 0.7157 Loss_G: 3.9809 D(x): 0.9339 D(G(z)): 0.4234 / 0.0284
[4/5][1450/1583] Loss_D: 0.9364 Loss_G: 5.0477 D(x): 0.8877 D(G(z)): 0.5022 / 0.0105
[4/5][1500/1583] Loss_D: 0.5947 Loss_G: 1.7611 D(x): 0.7653 D(G(z)): 0.2372 / 0.2149
[4/5][1550/1583] Loss_D: 1.4834 Loss_G: 0.6801 D(x): 0.3084 D(G(z)): 0.0380 / 0.5589
```

## 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.

**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.

```
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())
```