Shortcuts

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 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(x)))\)). From the paper, the GAN loss function is

\[\underset{G}{\text{min}} \underset{D}{\text{max}}V(D,G) = \mathbb{E}_{x\sim p_{data}(x)}\big[logD(x)\big] + \mathbb{E}_{z\sim p_{z}(z)}\big[log(1-D(G(z)))\big]\]

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

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)))
../_images/sphx_glr_dcgan_faces_tutorial_001.png

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

dcgan_generator

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=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
#  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=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:

\[\ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad l_n = - \left[ y_n \cdot \log x_n + (1 - y_n) \cdot \log (1 - x_n) \right]\]

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.8664  Loss_G: 4.9949  D(x): 0.5050    D(G(z)): 0.5928 / 0.0106
[0/5][50/1583]  Loss_D: 0.1164  Loss_G: 6.3327  D(x): 0.9821    D(G(z)): 0.0353 / 0.0088
[0/5][100/1583] Loss_D: 0.6500  Loss_G: 8.5506  D(x): 0.8983    D(G(z)): 0.3084 / 0.0008
[0/5][150/1583] Loss_D: 0.3882  Loss_G: 2.3167  D(x): 0.8348    D(G(z)): 0.0826 / 0.1773
[0/5][200/1583] Loss_D: 0.4996  Loss_G: 4.8283  D(x): 0.7188    D(G(z)): 0.0304 / 0.0122
[0/5][250/1583] Loss_D: 0.7112  Loss_G: 3.0257  D(x): 0.6858    D(G(z)): 0.1269 / 0.0874
[0/5][300/1583] Loss_D: 0.6014  Loss_G: 2.9924  D(x): 0.7573    D(G(z)): 0.2083 / 0.0730
[0/5][350/1583] Loss_D: 1.0553  Loss_G: 2.3669  D(x): 0.5003    D(G(z)): 0.0628 / 0.1624
[0/5][400/1583] Loss_D: 0.7078  Loss_G: 5.3654  D(x): 0.9079    D(G(z)): 0.4053 / 0.0130
[0/5][450/1583] Loss_D: 0.6259  Loss_G: 5.8745  D(x): 0.8932    D(G(z)): 0.3414 / 0.0064
[0/5][500/1583] Loss_D: 0.6442  Loss_G: 3.9164  D(x): 0.7826    D(G(z)): 0.2192 / 0.0359
[0/5][550/1583] Loss_D: 0.5650  Loss_G: 4.2448  D(x): 0.8038    D(G(z)): 0.2045 / 0.0262
[0/5][600/1583] Loss_D: 0.8724  Loss_G: 8.5326  D(x): 0.9339    D(G(z)): 0.4805 / 0.0006
[0/5][650/1583] Loss_D: 0.2510  Loss_G: 4.6053  D(x): 0.9121    D(G(z)): 0.1211 / 0.0174
[0/5][700/1583] Loss_D: 0.3778  Loss_G: 3.9419  D(x): 0.7693    D(G(z)): 0.0538 / 0.0308
[0/5][750/1583] Loss_D: 0.4424  Loss_G: 4.4343  D(x): 0.9226    D(G(z)): 0.2667 / 0.0174
[0/5][800/1583] Loss_D: 0.2920  Loss_G: 4.5266  D(x): 0.8288    D(G(z)): 0.0636 / 0.0200
[0/5][850/1583] Loss_D: 0.8617  Loss_G: 7.8081  D(x): 0.9332    D(G(z)): 0.4871 / 0.0010
[0/5][900/1583] Loss_D: 0.4552  Loss_G: 3.1839  D(x): 0.7460    D(G(z)): 0.0812 / 0.0722
[0/5][950/1583] Loss_D: 0.2615  Loss_G: 4.3918  D(x): 0.8956    D(G(z)): 0.1195 / 0.0237
[0/5][1000/1583]        Loss_D: 0.8312  Loss_G: 1.9589  D(x): 0.5710    D(G(z)): 0.0525 / 0.2147
[0/5][1050/1583]        Loss_D: 0.3988  Loss_G: 5.1550  D(x): 0.8943    D(G(z)): 0.2070 / 0.0102
[0/5][1100/1583]        Loss_D: 0.4076  Loss_G: 2.7323  D(x): 0.8034    D(G(z)): 0.1133 / 0.1005
[0/5][1150/1583]        Loss_D: 1.2152  Loss_G: 1.0146  D(x): 0.4353    D(G(z)): 0.0423 / 0.4245
[0/5][1200/1583]        Loss_D: 0.7570  Loss_G: 6.6842  D(x): 0.8981    D(G(z)): 0.4155 / 0.0035
[0/5][1250/1583]        Loss_D: 0.5240  Loss_G: 4.2630  D(x): 0.8281    D(G(z)): 0.2270 / 0.0226
[0/5][1300/1583]        Loss_D: 0.4874  Loss_G: 3.8270  D(x): 0.8750    D(G(z)): 0.2513 / 0.0325
[0/5][1350/1583]        Loss_D: 0.4722  Loss_G: 4.4401  D(x): 0.9174    D(G(z)): 0.2869 / 0.0186
[0/5][1400/1583]        Loss_D: 0.4843  Loss_G: 3.1688  D(x): 0.8548    D(G(z)): 0.2186 / 0.0695
[0/5][1450/1583]        Loss_D: 0.8983  Loss_G: 6.8422  D(x): 0.8979    D(G(z)): 0.4802 / 0.0026
[0/5][1500/1583]        Loss_D: 0.4259  Loss_G: 3.0975  D(x): 0.7808    D(G(z)): 0.1153 / 0.0658
[0/5][1550/1583]        Loss_D: 0.5618  Loss_G: 3.2871  D(x): 0.8243    D(G(z)): 0.2453 / 0.0603
[1/5][0/1583]   Loss_D: 0.4305  Loss_G: 3.4571  D(x): 0.7496    D(G(z)): 0.0625 / 0.0508
[1/5][50/1583]  Loss_D: 0.3509  Loss_G: 3.8943  D(x): 0.8236    D(G(z)): 0.0963 / 0.0344
[1/5][100/1583] Loss_D: 0.3889  Loss_G: 3.5543  D(x): 0.7929    D(G(z)): 0.1042 / 0.0470
[1/5][150/1583] Loss_D: 1.1344  Loss_G: 5.9704  D(x): 0.9539    D(G(z)): 0.6008 / 0.0054
[1/5][200/1583] Loss_D: 0.8094  Loss_G: 5.2500  D(x): 0.9470    D(G(z)): 0.4703 / 0.0097
[1/5][250/1583] Loss_D: 0.5325  Loss_G: 4.6564  D(x): 0.8822    D(G(z)): 0.2936 / 0.0155
[1/5][300/1583] Loss_D: 0.4475  Loss_G: 3.5293  D(x): 0.8081    D(G(z)): 0.1607 / 0.0403
[1/5][350/1583] Loss_D: 0.6466  Loss_G: 4.7204  D(x): 0.9084    D(G(z)): 0.3730 / 0.0152
[1/5][400/1583] Loss_D: 0.4475  Loss_G: 4.4130  D(x): 0.9334    D(G(z)): 0.2870 / 0.0199
[1/5][450/1583] Loss_D: 0.5445  Loss_G: 4.2882  D(x): 0.9132    D(G(z)): 0.3155 / 0.0246
[1/5][500/1583] Loss_D: 0.4090  Loss_G: 3.3560  D(x): 0.7937    D(G(z)): 0.1252 / 0.0511
[1/5][550/1583] Loss_D: 0.7900  Loss_G: 3.2994  D(x): 0.6804    D(G(z)): 0.2317 / 0.0648
[1/5][600/1583] Loss_D: 0.8600  Loss_G: 2.1912  D(x): 0.5798    D(G(z)): 0.1380 / 0.1600
[1/5][650/1583] Loss_D: 0.5619  Loss_G: 2.2430  D(x): 0.7028    D(G(z)): 0.1054 / 0.1410
[1/5][700/1583] Loss_D: 0.4090  Loss_G: 2.9897  D(x): 0.7556    D(G(z)): 0.0720 / 0.0819
[1/5][750/1583] Loss_D: 1.0678  Loss_G: 5.9937  D(x): 0.9666    D(G(z)): 0.5960 / 0.0045
[1/5][800/1583] Loss_D: 0.5858  Loss_G: 3.5338  D(x): 0.8912    D(G(z)): 0.3212 / 0.0533
[1/5][850/1583] Loss_D: 0.5105  Loss_G: 2.3191  D(x): 0.6867    D(G(z)): 0.0748 / 0.1284
[1/5][900/1583] Loss_D: 0.4819  Loss_G: 3.6504  D(x): 0.8348    D(G(z)): 0.2189 / 0.0376
[1/5][950/1583] Loss_D: 2.5887  Loss_G: 7.0482  D(x): 0.9870    D(G(z)): 0.8696 / 0.0034
[1/5][1000/1583]        Loss_D: 0.6032  Loss_G: 2.5206  D(x): 0.6502    D(G(z)): 0.0787 / 0.1100
[1/5][1050/1583]        Loss_D: 0.3534  Loss_G: 3.1873  D(x): 0.8904    D(G(z)): 0.1903 / 0.0574
[1/5][1100/1583]        Loss_D: 0.4637  Loss_G: 3.1668  D(x): 0.8057    D(G(z)): 0.1707 / 0.0632
[1/5][1150/1583]        Loss_D: 0.6998  Loss_G: 3.2717  D(x): 0.8345    D(G(z)): 0.3467 / 0.0524
[1/5][1200/1583]        Loss_D: 0.4073  Loss_G: 2.9885  D(x): 0.8461    D(G(z)): 0.1888 / 0.0714
[1/5][1250/1583]        Loss_D: 0.5090  Loss_G: 1.9835  D(x): 0.7045    D(G(z)): 0.0921 / 0.1780
[1/5][1300/1583]        Loss_D: 0.7495  Loss_G: 3.9293  D(x): 0.9240    D(G(z)): 0.4359 / 0.0335
[1/5][1350/1583]        Loss_D: 0.5585  Loss_G: 2.8623  D(x): 0.7890    D(G(z)): 0.2340 / 0.0779
[1/5][1400/1583]        Loss_D: 0.4779  Loss_G: 2.9822  D(x): 0.7271    D(G(z)): 0.0986 / 0.0808
[1/5][1450/1583]        Loss_D: 1.6573  Loss_G: 1.4877  D(x): 0.2696    D(G(z)): 0.0186 / 0.3113
[1/5][1500/1583]        Loss_D: 0.6673  Loss_G: 2.3133  D(x): 0.6610    D(G(z)): 0.1353 / 0.1436
[1/5][1550/1583]        Loss_D: 1.2182  Loss_G: 4.5559  D(x): 0.9353    D(G(z)): 0.6044 / 0.0223
[2/5][0/1583]   Loss_D: 0.5260  Loss_G: 2.3830  D(x): 0.7460    D(G(z)): 0.1696 / 0.1187
[2/5][50/1583]  Loss_D: 0.6826  Loss_G: 2.1603  D(x): 0.6282    D(G(z)): 0.1300 / 0.1499
[2/5][100/1583] Loss_D: 0.5114  Loss_G: 2.4472  D(x): 0.7099    D(G(z)): 0.1078 / 0.1169
[2/5][150/1583] Loss_D: 1.0720  Loss_G: 4.4930  D(x): 0.9212    D(G(z)): 0.5647 / 0.0176
[2/5][200/1583] Loss_D: 0.4492  Loss_G: 2.6146  D(x): 0.8598    D(G(z)): 0.2218 / 0.0988
[2/5][250/1583] Loss_D: 0.6255  Loss_G: 2.4640  D(x): 0.6118    D(G(z)): 0.0442 / 0.1201
[2/5][300/1583] Loss_D: 0.6009  Loss_G: 3.3765  D(x): 0.8803    D(G(z)): 0.3391 / 0.0467
[2/5][350/1583] Loss_D: 0.7020  Loss_G: 3.7924  D(x): 0.8935    D(G(z)): 0.4192 / 0.0294
[2/5][400/1583] Loss_D: 1.9287  Loss_G: 0.4761  D(x): 0.2297    D(G(z)): 0.0488 / 0.6724
[2/5][450/1583] Loss_D: 0.6189  Loss_G: 3.1436  D(x): 0.8498    D(G(z)): 0.3301 / 0.0581
[2/5][500/1583] Loss_D: 0.6772  Loss_G: 3.1658  D(x): 0.8838    D(G(z)): 0.3865 / 0.0577
[2/5][550/1583] Loss_D: 0.9952  Loss_G: 1.1167  D(x): 0.4631    D(G(z)): 0.0971 / 0.3798
[2/5][600/1583] Loss_D: 0.6339  Loss_G: 1.9277  D(x): 0.6725    D(G(z)): 0.1593 / 0.1778
[2/5][650/1583] Loss_D: 0.6164  Loss_G: 2.0238  D(x): 0.6618    D(G(z)): 0.1162 / 0.1631
[2/5][700/1583] Loss_D: 0.6668  Loss_G: 3.4620  D(x): 0.8727    D(G(z)): 0.3600 / 0.0419
[2/5][750/1583] Loss_D: 0.5204  Loss_G: 2.2023  D(x): 0.6693    D(G(z)): 0.0692 / 0.1474
[2/5][800/1583] Loss_D: 0.7820  Loss_G: 0.8576  D(x): 0.5554    D(G(z)): 0.1009 / 0.4613
[2/5][850/1583] Loss_D: 0.8125  Loss_G: 2.5283  D(x): 0.7835    D(G(z)): 0.3851 / 0.1010
[2/5][900/1583] Loss_D: 0.5450  Loss_G: 2.7598  D(x): 0.8645    D(G(z)): 0.2970 / 0.0797
[2/5][950/1583] Loss_D: 0.5866  Loss_G: 3.2705  D(x): 0.8776    D(G(z)): 0.3340 / 0.0526
[2/5][1000/1583]        Loss_D: 0.6416  Loss_G: 3.1707  D(x): 0.8074    D(G(z)): 0.3130 / 0.0564
[2/5][1050/1583]        Loss_D: 0.7074  Loss_G: 1.0624  D(x): 0.5846    D(G(z)): 0.0945 / 0.3938
[2/5][1100/1583]        Loss_D: 1.1414  Loss_G: 5.0316  D(x): 0.8998    D(G(z)): 0.5922 / 0.0102
[2/5][1150/1583]        Loss_D: 0.7948  Loss_G: 1.7607  D(x): 0.5557    D(G(z)): 0.0907 / 0.2180
[2/5][1200/1583]        Loss_D: 0.7528  Loss_G: 3.0219  D(x): 0.8710    D(G(z)): 0.4185 / 0.0622
[2/5][1250/1583]        Loss_D: 1.0173  Loss_G: 2.6637  D(x): 0.6454    D(G(z)): 0.3590 / 0.0959
[2/5][1300/1583]        Loss_D: 0.5150  Loss_G: 3.2834  D(x): 0.8053    D(G(z)): 0.2168 / 0.0596
[2/5][1350/1583]        Loss_D: 0.5156  Loss_G: 3.2547  D(x): 0.8674    D(G(z)): 0.2880 / 0.0496
[2/5][1400/1583]        Loss_D: 0.6287  Loss_G: 2.2635  D(x): 0.7251    D(G(z)): 0.2252 / 0.1301
[2/5][1450/1583]        Loss_D: 0.5374  Loss_G: 3.3125  D(x): 0.8112    D(G(z)): 0.2470 / 0.0514
[2/5][1500/1583]        Loss_D: 0.5558  Loss_G: 2.3804  D(x): 0.7956    D(G(z)): 0.2478 / 0.1176
[2/5][1550/1583]        Loss_D: 1.3468  Loss_G: 0.1723  D(x): 0.3568    D(G(z)): 0.0347 / 0.8570
[3/5][0/1583]   Loss_D: 0.5730  Loss_G: 1.9957  D(x): 0.7489    D(G(z)): 0.2090 / 0.1668
[3/5][50/1583]  Loss_D: 0.7140  Loss_G: 1.1195  D(x): 0.6209    D(G(z)): 0.1602 / 0.3818
[3/5][100/1583] Loss_D: 1.2946  Loss_G: 0.4481  D(x): 0.3415    D(G(z)): 0.0226 / 0.6707
[3/5][150/1583] Loss_D: 0.8376  Loss_G: 3.2857  D(x): 0.8827    D(G(z)): 0.4568 / 0.0486
[3/5][200/1583] Loss_D: 0.5578  Loss_G: 3.6264  D(x): 0.8621    D(G(z)): 0.3113 / 0.0336
[3/5][250/1583] Loss_D: 0.4769  Loss_G: 2.3588  D(x): 0.8131    D(G(z)): 0.2136 / 0.1177
[3/5][300/1583] Loss_D: 0.6321  Loss_G: 2.4122  D(x): 0.8349    D(G(z)): 0.3230 / 0.1159
[3/5][350/1583] Loss_D: 0.6285  Loss_G: 2.0063  D(x): 0.7119    D(G(z)): 0.2033 / 0.1629
[3/5][400/1583] Loss_D: 0.4438  Loss_G: 2.7762  D(x): 0.7756    D(G(z)): 0.1375 / 0.0860
[3/5][450/1583] Loss_D: 0.7211  Loss_G: 2.5315  D(x): 0.7283    D(G(z)): 0.2872 / 0.1019
[3/5][500/1583] Loss_D: 0.5265  Loss_G: 2.0160  D(x): 0.7936    D(G(z)): 0.2246 / 0.1660
[3/5][550/1583] Loss_D: 0.8631  Loss_G: 3.2266  D(x): 0.7293    D(G(z)): 0.3661 / 0.0560
[3/5][600/1583] Loss_D: 0.8367  Loss_G: 0.8854  D(x): 0.5442    D(G(z)): 0.1096 / 0.4430
[3/5][650/1583] Loss_D: 0.5915  Loss_G: 2.5472  D(x): 0.7888    D(G(z)): 0.2597 / 0.1045
[3/5][700/1583] Loss_D: 0.6117  Loss_G: 3.0374  D(x): 0.8493    D(G(z)): 0.3133 / 0.0681
[3/5][750/1583] Loss_D: 0.8155  Loss_G: 1.3866  D(x): 0.6382    D(G(z)): 0.2545 / 0.2864
[3/5][800/1583] Loss_D: 0.5261  Loss_G: 2.9280  D(x): 0.8175    D(G(z)): 0.2480 / 0.0681
[3/5][850/1583] Loss_D: 0.5661  Loss_G: 2.4623  D(x): 0.8358    D(G(z)): 0.2892 / 0.1064
[3/5][900/1583] Loss_D: 0.6336  Loss_G: 3.2586  D(x): 0.8466    D(G(z)): 0.3399 / 0.0510
[3/5][950/1583] Loss_D: 0.5568  Loss_G: 3.3120  D(x): 0.8403    D(G(z)): 0.2827 / 0.0500
[3/5][1000/1583]        Loss_D: 0.5501  Loss_G: 1.8930  D(x): 0.7536    D(G(z)): 0.2043 / 0.1899
[3/5][1050/1583]        Loss_D: 0.8346  Loss_G: 1.3622  D(x): 0.5341    D(G(z)): 0.0915 / 0.3088
[3/5][1100/1583]        Loss_D: 0.6320  Loss_G: 3.1845  D(x): 0.8474    D(G(z)): 0.3426 / 0.0509
[3/5][1150/1583]        Loss_D: 0.7423  Loss_G: 2.2229  D(x): 0.7426    D(G(z)): 0.3102 / 0.1334
[3/5][1200/1583]        Loss_D: 1.0204  Loss_G: 3.7934  D(x): 0.8869    D(G(z)): 0.5414 / 0.0365
[3/5][1250/1583]        Loss_D: 0.9857  Loss_G: 1.3051  D(x): 0.4300    D(G(z)): 0.0338 / 0.3216
[3/5][1300/1583]        Loss_D: 0.5129  Loss_G: 2.0869  D(x): 0.7038    D(G(z)): 0.1073 / 0.1573
[3/5][1350/1583]        Loss_D: 0.6969  Loss_G: 1.8926  D(x): 0.7137    D(G(z)): 0.2508 / 0.1960
[3/5][1400/1583]        Loss_D: 0.6847  Loss_G: 1.1432  D(x): 0.6320    D(G(z)): 0.1387 / 0.3572
[3/5][1450/1583]        Loss_D: 0.7086  Loss_G: 1.9519  D(x): 0.7067    D(G(z)): 0.2623 / 0.1694
[3/5][1500/1583]        Loss_D: 1.5900  Loss_G: 0.7564  D(x): 0.2720    D(G(z)): 0.0319 / 0.5317
[3/5][1550/1583]        Loss_D: 0.5878  Loss_G: 1.9759  D(x): 0.6829    D(G(z)): 0.1394 / 0.1718
[4/5][0/1583]   Loss_D: 1.2915  Loss_G: 4.6033  D(x): 0.9326    D(G(z)): 0.6473 / 0.0147
[4/5][50/1583]  Loss_D: 0.5628  Loss_G: 2.6636  D(x): 0.8021    D(G(z)): 0.2602 / 0.0878
[4/5][100/1583] Loss_D: 0.7918  Loss_G: 3.5693  D(x): 0.8590    D(G(z)): 0.4298 / 0.0400
[4/5][150/1583] Loss_D: 0.7076  Loss_G: 1.4158  D(x): 0.6032    D(G(z)): 0.1286 / 0.2896
[4/5][200/1583] Loss_D: 0.9885  Loss_G: 4.2181  D(x): 0.8642    D(G(z)): 0.5119 / 0.0220
[4/5][250/1583] Loss_D: 0.5747  Loss_G: 2.3627  D(x): 0.7413    D(G(z)): 0.1956 / 0.1242
[4/5][300/1583] Loss_D: 1.2252  Loss_G: 3.8262  D(x): 0.8949    D(G(z)): 0.6160 / 0.0326
[4/5][350/1583] Loss_D: 0.5965  Loss_G: 2.7654  D(x): 0.8323    D(G(z)): 0.2956 / 0.0843
[4/5][400/1583] Loss_D: 0.5151  Loss_G: 3.3570  D(x): 0.9149    D(G(z)): 0.3180 / 0.0475
[4/5][450/1583] Loss_D: 0.6096  Loss_G: 2.0857  D(x): 0.7131    D(G(z)): 0.1878 / 0.1614
[4/5][500/1583] Loss_D: 0.6638  Loss_G: 2.2867  D(x): 0.7521    D(G(z)): 0.2703 / 0.1239
[4/5][550/1583] Loss_D: 0.7364  Loss_G: 1.5381  D(x): 0.6093    D(G(z)): 0.1566 / 0.2562
[4/5][600/1583] Loss_D: 0.4541  Loss_G: 2.4904  D(x): 0.7480    D(G(z)): 0.1169 / 0.1153
[4/5][650/1583] Loss_D: 0.4797  Loss_G: 2.5566  D(x): 0.8418    D(G(z)): 0.2380 / 0.0958
[4/5][700/1583] Loss_D: 0.8636  Loss_G: 4.6097  D(x): 0.9460    D(G(z)): 0.5171 / 0.0141
[4/5][750/1583] Loss_D: 0.9391  Loss_G: 0.8470  D(x): 0.5283    D(G(z)): 0.1705 / 0.4711
[4/5][800/1583] Loss_D: 0.9065  Loss_G: 1.2562  D(x): 0.5222    D(G(z)): 0.1288 / 0.3211
[4/5][850/1583] Loss_D: 0.5825  Loss_G: 2.9573  D(x): 0.8296    D(G(z)): 0.2920 / 0.0677
[4/5][900/1583] Loss_D: 0.8524  Loss_G: 1.5152  D(x): 0.5367    D(G(z)): 0.1316 / 0.2671
[4/5][950/1583] Loss_D: 0.5136  Loss_G: 2.5986  D(x): 0.7812    D(G(z)): 0.2083 / 0.0969
[4/5][1000/1583]        Loss_D: 0.6139  Loss_G: 2.3941  D(x): 0.7550    D(G(z)): 0.2420 / 0.1131
[4/5][1050/1583]        Loss_D: 0.5659  Loss_G: 2.7736  D(x): 0.7934    D(G(z)): 0.2486 / 0.0812
[4/5][1100/1583]        Loss_D: 1.2266  Loss_G: 3.9759  D(x): 0.9701    D(G(z)): 0.6483 / 0.0324
[4/5][1150/1583]        Loss_D: 0.7776  Loss_G: 3.4581  D(x): 0.9172    D(G(z)): 0.4394 / 0.0438
[4/5][1200/1583]        Loss_D: 1.7693  Loss_G: 5.6766  D(x): 0.9839    D(G(z)): 0.7510 / 0.0068
[4/5][1250/1583]        Loss_D: 0.8701  Loss_G: 1.5499  D(x): 0.4913    D(G(z)): 0.0567 / 0.2734
[4/5][1300/1583]        Loss_D: 0.5922  Loss_G: 2.0101  D(x): 0.7149    D(G(z)): 0.1728 / 0.1750
[4/5][1350/1583]        Loss_D: 0.6841  Loss_G: 2.7521  D(x): 0.7518    D(G(z)): 0.2826 / 0.0826
[4/5][1400/1583]        Loss_D: 0.6020  Loss_G: 2.9772  D(x): 0.8505    D(G(z)): 0.3311 / 0.0622
[4/5][1450/1583]        Loss_D: 0.9551  Loss_G: 2.5080  D(x): 0.7079    D(G(z)): 0.4012 / 0.1162
[4/5][1500/1583]        Loss_D: 0.5961  Loss_G: 1.5754  D(x): 0.6590    D(G(z)): 0.1153 / 0.2510
[4/5][1550/1583]        Loss_D: 0.5623  Loss_G: 2.9591  D(x): 0.8391    D(G(z)): 0.2910 / 0.0667

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()
../_images/sphx_glr_dcgan_faces_tutorial_002.png

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())
../_images/sphx_glr_dcgan_faces_tutorial_003.png

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()
../_images/sphx_glr_dcgan_faces_tutorial_004.png

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: ( 270 minutes 59.673 seconds)

Gallery generated by Sphinx-Gallery