.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "beginner/dcgan_faces_tutorial.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_beginner_dcgan_faces_tutorial.py: DCGAN Tutorial ============== **Author**: `Nathan Inkawhich `__ .. GENERATED FROM PYTHON SOURCE LINES 12-114 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 :math:`x` be data representing an image. :math:`D(x)` is the discriminator network which outputs the (scalar) probability that :math:`x` came from training data rather than the generator. Here, since we are dealing with images, the input to :math:`D(x)` is an image of CHW size 3x64x64. Intuitively, :math:`D(x)` should be HIGH when :math:`x` comes from training data and LOW when :math:`x` comes from the generator. :math:`D(x)` can also be thought of as a traditional binary classifier. For the generator’s notation, let :math:`z` be a latent space vector sampled from a standard normal distribution. :math:`G(z)` represents the generator function which maps the latent vector :math:`z` to data-space. The goal of :math:`G` is to estimate the distribution that the training data comes from (:math:`p_{data}`) so it can generate fake samples from that estimated distribution (:math:`p_g`). So, :math:`D(G(z))` is the probability (scalar) that the output of the generator :math:`G` is a real image. As described in `Goodfellow’s paper `__, :math:`D` and :math:`G` play a minimax game in which :math:`D` tries to maximize the probability it correctly classifies reals and fakes (:math:`logD(x)`), and :math:`G` tries to minimize the probability that :math:`D` will predict its outputs are fake (:math:`log(1-D(G(z)))`). From the paper, the GAN loss function is .. math:: \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 :math:`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, :math:`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. .. GENERATED FROM PYTHON SOURCE LINES 114-141 .. code-block:: default #%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 .. rst-class:: sphx-glr-script-out .. code-block:: none Random Seed: 999 .. GENERATED FROM PYTHON SOURCE LINES 142-176 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. .. GENERATED FROM PYTHON SOURCE LINES 176-215 .. code-block:: default # 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 .. GENERATED FROM PYTHON SOURCE LINES 216-245 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: .. code-block:: sh /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. .. GENERATED FROM PYTHON SOURCE LINES 245-271 .. code-block:: default # 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() .. image-sg:: /beginner/images/sphx_glr_dcgan_faces_tutorial_001.png :alt: Training Images :srcset: /beginner/images/sphx_glr_dcgan_faces_tutorial_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 272-290 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. .. GENERATED FROM PYTHON SOURCE LINES 290-301 .. code-block:: default # 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) .. GENERATED FROM PYTHON SOURCE LINES 302-328 Generator ~~~~~~~~~ The generator, :math:`G`, is designed to map the latent space vector (:math:`z`) to data-space. Since our data are images, converting :math:`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 :math:`[-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. .. figure:: /_static/img/dcgan_generator.png :alt: dcgan_generator 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. .. GENERATED FROM PYTHON SOURCE LINES 328-362 .. code-block:: default # 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) .. GENERATED FROM PYTHON SOURCE LINES 363-367 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. .. GENERATED FROM PYTHON SOURCE LINES 367-383 .. code-block:: default # 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) .. rst-class:: sphx-glr-script-out .. code-block:: none 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() ) ) .. GENERATED FROM PYTHON SOURCE LINES 384-401 Discriminator ~~~~~~~~~~~~~ As mentioned, the discriminator, :math:`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, :math:`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 :math:`G` and :math:`D`. .. GENERATED FROM PYTHON SOURCE LINES 403-404 Discriminator Code .. GENERATED FROM PYTHON SOURCE LINES 404-434 .. code-block:: default 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) .. GENERATED FROM PYTHON SOURCE LINES 435-438 Now, as with the generator, we can create the discriminator, apply the ``weights_init`` function, and print the model’s structure. .. GENERATED FROM PYTHON SOURCE LINES 438-454 .. code-block:: default # 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) .. rst-class:: sphx-glr-script-out .. code-block:: none 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() ) ) .. GENERATED FROM PYTHON SOURCE LINES 455-486 Loss Functions and Optimizers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ With :math:`D` and :math:`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: .. math:: \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. :math:`log(D(x))` and :math:`log(1-D(G(z)))`). We can specify what part of the BCE equation to use with the :math:`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 :math:`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 :math:`D` and :math:`G`, and this is also the convention used in the original GAN paper. Finally, we set up two separate optimizers, one for :math:`D` and one for :math:`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 :math:`G`, and over the iterations we will see images form out of the noise. .. GENERATED FROM PYTHON SOURCE LINES 486-503 .. code-block:: default # 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)) .. GENERATED FROM PYTHON SOURCE LINES 504-572 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 :math:`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 :math:`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 :math:`D`, calculate the loss (:math:`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 :math:`D`, calculate the loss (:math:`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 :math:`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 :math:`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 :math:`log(x)` part of the ``BCELoss`` (rather than the :math:`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 (:math:`log(D(x)) + log(1 - D(G(z)))`). - **Loss_G** - generator loss calculated as :math:`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. .. GENERATED FROM PYTHON SOURCE LINES 572-656 .. code-block:: default # 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 .. rst-class:: sphx-glr-script-out .. code-block:: none Starting Training Loop... [0/5][0/1583] Loss_D: 1.4640 Loss_G: 6.9360 D(x): 0.7143 D(G(z)): 0.5877 / 0.0017 [0/5][50/1583] Loss_D: 0.0174 Loss_G: 23.7368 D(x): 0.9881 D(G(z)): 0.0000 / 0.0000 [0/5][100/1583] Loss_D: 0.5983 Loss_G: 9.9471 D(x): 0.9715 D(G(z)): 0.3122 / 0.0003 [0/5][150/1583] Loss_D: 0.4940 Loss_G: 5.6772 D(x): 0.7028 D(G(z)): 0.0241 / 0.0091 [0/5][200/1583] Loss_D: 0.5931 Loss_G: 7.1186 D(x): 0.9423 D(G(z)): 0.3016 / 0.0018 [0/5][250/1583] Loss_D: 0.3846 Loss_G: 3.2697 D(x): 0.7663 D(G(z)): 0.0573 / 0.0739 [0/5][300/1583] Loss_D: 1.3306 Loss_G: 8.3204 D(x): 0.8768 D(G(z)): 0.6353 / 0.0009 [0/5][350/1583] Loss_D: 0.6451 Loss_G: 6.0499 D(x): 0.9025 D(G(z)): 0.3673 / 0.0060 [0/5][400/1583] Loss_D: 0.4211 Loss_G: 3.7316 D(x): 0.8407 D(G(z)): 0.1586 / 0.0392 [0/5][450/1583] Loss_D: 0.6569 Loss_G: 2.4818 D(x): 0.6437 D(G(z)): 0.0858 / 0.1129 [0/5][500/1583] Loss_D: 1.2208 Loss_G: 2.9943 D(x): 0.4179 D(G(z)): 0.0109 / 0.1133 [0/5][550/1583] Loss_D: 0.3400 Loss_G: 4.7669 D(x): 0.9135 D(G(z)): 0.1922 / 0.0145 [0/5][600/1583] Loss_D: 0.5756 Loss_G: 4.8500 D(x): 0.9189 D(G(z)): 0.3193 / 0.0187 [0/5][650/1583] Loss_D: 0.2470 Loss_G: 4.1606 D(x): 0.9460 D(G(z)): 0.1545 / 0.0250 [0/5][700/1583] Loss_D: 0.3887 Loss_G: 4.1884 D(x): 0.8518 D(G(z)): 0.1562 / 0.0297 [0/5][750/1583] Loss_D: 0.5353 Loss_G: 4.1742 D(x): 0.8034 D(G(z)): 0.1958 / 0.0302 [0/5][800/1583] Loss_D: 0.3213 Loss_G: 5.8919 D(x): 0.9076 D(G(z)): 0.1572 / 0.0065 [0/5][850/1583] Loss_D: 0.8850 Loss_G: 7.4333 D(x): 0.9258 D(G(z)): 0.4449 / 0.0017 [0/5][900/1583] Loss_D: 1.2624 Loss_G: 10.0392 D(x): 0.9896 D(G(z)): 0.6361 / 0.0002 [0/5][950/1583] Loss_D: 0.8802 Loss_G: 6.9221 D(x): 0.5527 D(G(z)): 0.0039 / 0.0045 [0/5][1000/1583] Loss_D: 0.5799 Loss_G: 3.1800 D(x): 0.7062 D(G(z)): 0.0762 / 0.0884 [0/5][1050/1583] Loss_D: 0.9647 Loss_G: 6.6894 D(x): 0.9429 D(G(z)): 0.5270 / 0.0035 [0/5][1100/1583] Loss_D: 0.5624 Loss_G: 3.6715 D(x): 0.7944 D(G(z)): 0.2069 / 0.0445 [0/5][1150/1583] Loss_D: 0.6205 Loss_G: 4.8995 D(x): 0.8634 D(G(z)): 0.3046 / 0.0169 [0/5][1200/1583] Loss_D: 0.2569 Loss_G: 4.2945 D(x): 0.9455 D(G(z)): 0.1528 / 0.0255 [0/5][1250/1583] Loss_D: 0.4921 Loss_G: 3.2500 D(x): 0.8152 D(G(z)): 0.1892 / 0.0753 [0/5][1300/1583] Loss_D: 0.4068 Loss_G: 3.7702 D(x): 0.8153 D(G(z)): 0.1335 / 0.0472 [0/5][1350/1583] Loss_D: 1.1704 Loss_G: 7.3408 D(x): 0.9443 D(G(z)): 0.5863 / 0.0022 [0/5][1400/1583] Loss_D: 0.6111 Loss_G: 2.2676 D(x): 0.6714 D(G(z)): 0.0793 / 0.1510 [0/5][1450/1583] Loss_D: 0.7817 Loss_G: 4.0744 D(x): 0.7915 D(G(z)): 0.3573 / 0.0242 [0/5][1500/1583] Loss_D: 0.7177 Loss_G: 1.9253 D(x): 0.5770 D(G(z)): 0.0257 / 0.1909 [0/5][1550/1583] Loss_D: 0.4518 Loss_G: 2.8314 D(x): 0.7991 D(G(z)): 0.1479 / 0.0885 [1/5][0/1583] Loss_D: 0.4267 Loss_G: 4.5150 D(x): 0.8976 D(G(z)): 0.2401 / 0.0196 [1/5][50/1583] Loss_D: 0.5106 Loss_G: 2.7800 D(x): 0.7073 D(G(z)): 0.0663 / 0.0932 [1/5][100/1583] Loss_D: 0.6300 Loss_G: 1.8648 D(x): 0.6557 D(G(z)): 0.0756 / 0.2118 [1/5][150/1583] Loss_D: 1.1727 Loss_G: 5.1536 D(x): 0.8397 D(G(z)): 0.5261 / 0.0125 [1/5][200/1583] Loss_D: 0.4675 Loss_G: 2.9615 D(x): 0.7645 D(G(z)): 0.1400 / 0.0780 [1/5][250/1583] Loss_D: 0.7938 Loss_G: 3.1614 D(x): 0.6958 D(G(z)): 0.2248 / 0.0678 [1/5][300/1583] Loss_D: 0.9869 Loss_G: 5.9243 D(x): 0.9619 D(G(z)): 0.5349 / 0.0063 [1/5][350/1583] Loss_D: 0.5178 Loss_G: 3.0236 D(x): 0.7795 D(G(z)): 0.1769 / 0.0700 [1/5][400/1583] Loss_D: 1.4509 Loss_G: 2.7187 D(x): 0.3278 D(G(z)): 0.0133 / 0.1273 [1/5][450/1583] Loss_D: 0.5530 Loss_G: 4.8110 D(x): 0.9151 D(G(z)): 0.3237 / 0.0160 [1/5][500/1583] Loss_D: 0.4621 Loss_G: 4.1158 D(x): 0.8720 D(G(z)): 0.2278 / 0.0293 [1/5][550/1583] Loss_D: 0.4987 Loss_G: 4.0199 D(x): 0.8533 D(G(z)): 0.2367 / 0.0287 [1/5][600/1583] Loss_D: 1.0630 Loss_G: 4.6502 D(x): 0.9145 D(G(z)): 0.5018 / 0.0218 [1/5][650/1583] Loss_D: 0.6081 Loss_G: 4.3172 D(x): 0.8670 D(G(z)): 0.3312 / 0.0221 [1/5][700/1583] Loss_D: 0.4703 Loss_G: 2.4900 D(x): 0.7538 D(G(z)): 0.1245 / 0.1188 [1/5][750/1583] Loss_D: 0.4827 Loss_G: 2.2941 D(x): 0.7372 D(G(z)): 0.1105 / 0.1300 [1/5][800/1583] Loss_D: 0.4013 Loss_G: 3.8850 D(x): 0.8895 D(G(z)): 0.2179 / 0.0324 [1/5][850/1583] Loss_D: 0.7245 Loss_G: 1.9088 D(x): 0.6100 D(G(z)): 0.0950 / 0.1898 [1/5][900/1583] Loss_D: 0.8372 Loss_G: 1.2346 D(x): 0.5232 D(G(z)): 0.0332 / 0.3633 [1/5][950/1583] Loss_D: 0.5561 Loss_G: 3.2048 D(x): 0.7660 D(G(z)): 0.2035 / 0.0594 [1/5][1000/1583] Loss_D: 0.6859 Loss_G: 1.6347 D(x): 0.5764 D(G(z)): 0.0435 / 0.2540 [1/5][1050/1583] Loss_D: 0.6785 Loss_G: 4.3244 D(x): 0.9066 D(G(z)): 0.3835 / 0.0203 [1/5][1100/1583] Loss_D: 0.4835 Loss_G: 2.4080 D(x): 0.7428 D(G(z)): 0.1073 / 0.1147 [1/5][1150/1583] Loss_D: 0.5507 Loss_G: 2.5400 D(x): 0.7857 D(G(z)): 0.2182 / 0.1092 [1/5][1200/1583] Loss_D: 0.6054 Loss_G: 3.4802 D(x): 0.8263 D(G(z)): 0.2934 / 0.0441 [1/5][1250/1583] Loss_D: 0.4788 Loss_G: 2.3533 D(x): 0.7872 D(G(z)): 0.1698 / 0.1327 [1/5][1300/1583] Loss_D: 0.5314 Loss_G: 2.7018 D(x): 0.8273 D(G(z)): 0.2423 / 0.0921 [1/5][1350/1583] Loss_D: 0.8579 Loss_G: 4.6214 D(x): 0.9623 D(G(z)): 0.5089 / 0.0159 [1/5][1400/1583] Loss_D: 0.4919 Loss_G: 2.7656 D(x): 0.8122 D(G(z)): 0.2147 / 0.0864 [1/5][1450/1583] Loss_D: 0.4461 Loss_G: 3.0576 D(x): 0.8042 D(G(z)): 0.1798 / 0.0619 [1/5][1500/1583] Loss_D: 0.7182 Loss_G: 3.7270 D(x): 0.8553 D(G(z)): 0.3713 / 0.0382 [1/5][1550/1583] Loss_D: 0.6378 Loss_G: 3.7489 D(x): 0.8757 D(G(z)): 0.3523 / 0.0317 [2/5][0/1583] Loss_D: 0.3965 Loss_G: 2.6262 D(x): 0.7941 D(G(z)): 0.1247 / 0.0963 [2/5][50/1583] Loss_D: 0.6504 Loss_G: 3.9890 D(x): 0.9267 D(G(z)): 0.3865 / 0.0275 [2/5][100/1583] Loss_D: 0.6523 Loss_G: 3.8724 D(x): 0.8707 D(G(z)): 0.3613 / 0.0299 [2/5][150/1583] Loss_D: 0.7685 Loss_G: 3.9059 D(x): 0.9361 D(G(z)): 0.4534 / 0.0278 [2/5][200/1583] Loss_D: 0.6587 Loss_G: 1.9218 D(x): 0.6469 D(G(z)): 0.1291 / 0.1888 [2/5][250/1583] Loss_D: 0.6971 Loss_G: 2.2256 D(x): 0.6208 D(G(z)): 0.1226 / 0.1465 [2/5][300/1583] Loss_D: 0.5797 Loss_G: 2.4846 D(x): 0.7762 D(G(z)): 0.2434 / 0.1098 [2/5][350/1583] Loss_D: 0.4674 Loss_G: 1.8800 D(x): 0.8045 D(G(z)): 0.1903 / 0.1877 [2/5][400/1583] Loss_D: 0.6462 Loss_G: 1.9510 D(x): 0.7018 D(G(z)): 0.1935 / 0.1792 [2/5][450/1583] Loss_D: 0.9817 Loss_G: 4.2519 D(x): 0.9421 D(G(z)): 0.5381 / 0.0233 [2/5][500/1583] Loss_D: 0.7721 Loss_G: 1.0928 D(x): 0.5402 D(G(z)): 0.0316 / 0.3927 [2/5][550/1583] Loss_D: 0.6037 Loss_G: 2.6914 D(x): 0.7719 D(G(z)): 0.2504 / 0.0896 [2/5][600/1583] Loss_D: 1.4213 Loss_G: 5.4727 D(x): 0.9408 D(G(z)): 0.6792 / 0.0064 [2/5][650/1583] Loss_D: 0.7246 Loss_G: 1.7030 D(x): 0.6716 D(G(z)): 0.2184 / 0.2246 [2/5][700/1583] Loss_D: 0.6642 Loss_G: 3.3809 D(x): 0.8554 D(G(z)): 0.3438 / 0.0591 [2/5][750/1583] Loss_D: 0.6649 Loss_G: 2.0197 D(x): 0.7169 D(G(z)): 0.2333 / 0.1565 [2/5][800/1583] Loss_D: 0.4594 Loss_G: 2.6623 D(x): 0.8150 D(G(z)): 0.1930 / 0.0944 [2/5][850/1583] Loss_D: 1.1957 Loss_G: 3.1871 D(x): 0.7790 D(G(z)): 0.5576 / 0.0568 [2/5][900/1583] Loss_D: 0.6657 Loss_G: 1.5311 D(x): 0.7092 D(G(z)): 0.2122 / 0.2558 [2/5][950/1583] Loss_D: 0.6795 Loss_G: 1.4149 D(x): 0.6134 D(G(z)): 0.1195 / 0.2937 [2/5][1000/1583] Loss_D: 0.5995 Loss_G: 2.1744 D(x): 0.7325 D(G(z)): 0.2054 / 0.1484 [2/5][1050/1583] Loss_D: 0.6706 Loss_G: 1.6705 D(x): 0.6425 D(G(z)): 0.1414 / 0.2310 [2/5][1100/1583] Loss_D: 1.2840 Loss_G: 4.4620 D(x): 0.9736 D(G(z)): 0.6601 / 0.0225 [2/5][1150/1583] Loss_D: 0.7568 Loss_G: 3.1238 D(x): 0.8153 D(G(z)): 0.3717 / 0.0581 [2/5][1200/1583] Loss_D: 0.6331 Loss_G: 1.9048 D(x): 0.6799 D(G(z)): 0.1604 / 0.1814 [2/5][1250/1583] Loss_D: 0.5802 Loss_G: 2.4358 D(x): 0.7561 D(G(z)): 0.2194 / 0.1095 [2/5][1300/1583] Loss_D: 0.9613 Loss_G: 2.3290 D(x): 0.7463 D(G(z)): 0.3952 / 0.1349 [2/5][1350/1583] Loss_D: 0.5367 Loss_G: 1.7398 D(x): 0.7580 D(G(z)): 0.1898 / 0.2216 [2/5][1400/1583] Loss_D: 0.7762 Loss_G: 3.6246 D(x): 0.9006 D(G(z)): 0.4378 / 0.0364 [2/5][1450/1583] Loss_D: 0.7183 Loss_G: 4.0442 D(x): 0.8602 D(G(z)): 0.3857 / 0.0254 [2/5][1500/1583] Loss_D: 0.5416 Loss_G: 2.0642 D(x): 0.7393 D(G(z)): 0.1758 / 0.1532 [2/5][1550/1583] Loss_D: 0.5295 Loss_G: 1.7855 D(x): 0.6768 D(G(z)): 0.0886 / 0.2154 [3/5][0/1583] Loss_D: 0.8635 Loss_G: 1.7508 D(x): 0.4918 D(G(z)): 0.0280 / 0.2154 [3/5][50/1583] Loss_D: 0.8697 Loss_G: 0.7859 D(x): 0.5216 D(G(z)): 0.1124 / 0.4941 [3/5][100/1583] Loss_D: 0.8607 Loss_G: 4.5255 D(x): 0.9197 D(G(z)): 0.4973 / 0.0157 [3/5][150/1583] Loss_D: 0.4805 Loss_G: 2.3071 D(x): 0.7743 D(G(z)): 0.1742 / 0.1291 [3/5][200/1583] Loss_D: 0.4925 Loss_G: 2.6018 D(x): 0.7907 D(G(z)): 0.1970 / 0.0948 [3/5][250/1583] Loss_D: 0.7870 Loss_G: 3.3529 D(x): 0.8408 D(G(z)): 0.4050 / 0.0469 [3/5][300/1583] Loss_D: 0.5479 Loss_G: 1.7376 D(x): 0.7216 D(G(z)): 0.1592 / 0.2227 [3/5][350/1583] Loss_D: 0.8117 Loss_G: 3.4145 D(x): 0.9076 D(G(z)): 0.4685 / 0.0437 [3/5][400/1583] Loss_D: 0.4210 Loss_G: 2.3880 D(x): 0.7543 D(G(z)): 0.1047 / 0.1217 [3/5][450/1583] Loss_D: 1.5745 Loss_G: 0.2366 D(x): 0.2747 D(G(z)): 0.0361 / 0.8096 [3/5][500/1583] Loss_D: 0.7196 Loss_G: 2.1319 D(x): 0.7332 D(G(z)): 0.2935 / 0.1403 [3/5][550/1583] Loss_D: 0.5697 Loss_G: 2.6649 D(x): 0.8816 D(G(z)): 0.3210 / 0.0917 [3/5][600/1583] Loss_D: 0.7779 Loss_G: 1.2727 D(x): 0.5540 D(G(z)): 0.0855 / 0.3412 [3/5][650/1583] Loss_D: 0.4090 Loss_G: 2.6893 D(x): 0.8334 D(G(z)): 0.1835 / 0.0855 [3/5][700/1583] Loss_D: 0.8108 Loss_G: 3.8991 D(x): 0.9241 D(G(z)): 0.4716 / 0.0281 [3/5][750/1583] Loss_D: 0.9907 Loss_G: 4.7885 D(x): 0.9111 D(G(z)): 0.5402 / 0.0123 [3/5][800/1583] Loss_D: 0.4725 Loss_G: 2.3347 D(x): 0.7577 D(G(z)): 0.1400 / 0.1222 [3/5][850/1583] Loss_D: 1.5580 Loss_G: 4.9586 D(x): 0.8954 D(G(z)): 0.7085 / 0.0132 [3/5][900/1583] Loss_D: 0.5785 Loss_G: 1.6395 D(x): 0.6581 D(G(z)): 0.1003 / 0.2411 [3/5][950/1583] Loss_D: 0.6592 Loss_G: 1.0890 D(x): 0.5893 D(G(z)): 0.0451 / 0.3809 [3/5][1000/1583] Loss_D: 0.7280 Loss_G: 3.5368 D(x): 0.8898 D(G(z)): 0.4176 / 0.0409 [3/5][1050/1583] Loss_D: 0.7088 Loss_G: 3.4301 D(x): 0.8558 D(G(z)): 0.3845 / 0.0457 [3/5][1100/1583] Loss_D: 0.5651 Loss_G: 2.1150 D(x): 0.7602 D(G(z)): 0.2127 / 0.1532 [3/5][1150/1583] Loss_D: 0.5412 Loss_G: 1.7790 D(x): 0.6602 D(G(z)): 0.0801 / 0.2088 [3/5][1200/1583] Loss_D: 1.2277 Loss_G: 1.1464 D(x): 0.4864 D(G(z)): 0.2915 / 0.3665 [3/5][1250/1583] Loss_D: 0.7148 Loss_G: 1.3957 D(x): 0.5948 D(G(z)): 0.1076 / 0.2876 [3/5][1300/1583] Loss_D: 1.0675 Loss_G: 1.3018 D(x): 0.4056 D(G(z)): 0.0310 / 0.3355 [3/5][1350/1583] Loss_D: 0.8064 Loss_G: 0.7482 D(x): 0.5846 D(G(z)): 0.1453 / 0.5147 [3/5][1400/1583] Loss_D: 0.6032 Loss_G: 3.0601 D(x): 0.8474 D(G(z)): 0.3189 / 0.0590 [3/5][1450/1583] Loss_D: 0.5329 Loss_G: 2.8172 D(x): 0.8234 D(G(z)): 0.2567 / 0.0795 [3/5][1500/1583] Loss_D: 0.9292 Loss_G: 3.5544 D(x): 0.8686 D(G(z)): 0.4887 / 0.0410 [3/5][1550/1583] Loss_D: 0.5929 Loss_G: 2.9118 D(x): 0.8614 D(G(z)): 0.3239 / 0.0702 [4/5][0/1583] Loss_D: 0.5564 Loss_G: 2.7516 D(x): 0.8716 D(G(z)): 0.3145 / 0.0799 [4/5][50/1583] Loss_D: 1.0485 Loss_G: 0.6751 D(x): 0.4332 D(G(z)): 0.0675 / 0.5568 [4/5][100/1583] Loss_D: 0.6753 Loss_G: 1.4046 D(x): 0.6028 D(G(z)): 0.0882 / 0.2901 [4/5][150/1583] Loss_D: 0.5946 Loss_G: 1.7618 D(x): 0.6862 D(G(z)): 0.1488 / 0.2016 [4/5][200/1583] Loss_D: 0.4866 Loss_G: 2.2638 D(x): 0.7628 D(G(z)): 0.1633 / 0.1321 [4/5][250/1583] Loss_D: 0.7493 Loss_G: 1.0999 D(x): 0.5541 D(G(z)): 0.0659 / 0.3787 [4/5][300/1583] Loss_D: 1.0886 Loss_G: 4.6532 D(x): 0.9370 D(G(z)): 0.5811 / 0.0149 [4/5][350/1583] Loss_D: 0.6106 Loss_G: 1.9212 D(x): 0.6594 D(G(z)): 0.1322 / 0.1825 [4/5][400/1583] Loss_D: 0.5226 Loss_G: 2.9611 D(x): 0.8178 D(G(z)): 0.2378 / 0.0731 [4/5][450/1583] Loss_D: 1.0068 Loss_G: 1.3267 D(x): 0.4310 D(G(z)): 0.0375 / 0.3179 [4/5][500/1583] Loss_D: 3.1088 Loss_G: 0.1269 D(x): 0.0706 D(G(z)): 0.0061 / 0.8897 [4/5][550/1583] Loss_D: 1.7889 Loss_G: 0.4800 D(x): 0.2175 D(G(z)): 0.0143 / 0.6479 [4/5][600/1583] Loss_D: 0.6732 Loss_G: 3.5685 D(x): 0.8775 D(G(z)): 0.3879 / 0.0362 [4/5][650/1583] Loss_D: 0.5169 Loss_G: 2.1943 D(x): 0.7222 D(G(z)): 0.1349 / 0.1416 [4/5][700/1583] Loss_D: 0.4567 Loss_G: 2.4442 D(x): 0.7666 D(G(z)): 0.1410 / 0.1204 [4/5][750/1583] Loss_D: 0.5972 Loss_G: 2.2992 D(x): 0.6286 D(G(z)): 0.0670 / 0.1283 [4/5][800/1583] Loss_D: 0.5461 Loss_G: 1.9777 D(x): 0.7013 D(G(z)): 0.1318 / 0.1795 [4/5][850/1583] Loss_D: 0.6317 Loss_G: 2.2345 D(x): 0.6962 D(G(z)): 0.1854 / 0.1385 [4/5][900/1583] Loss_D: 0.6034 Loss_G: 3.2300 D(x): 0.8781 D(G(z)): 0.3448 / 0.0517 [4/5][950/1583] Loss_D: 0.6371 Loss_G: 2.7755 D(x): 0.8595 D(G(z)): 0.3357 / 0.0826 [4/5][1000/1583] Loss_D: 0.6077 Loss_G: 3.3958 D(x): 0.9026 D(G(z)): 0.3604 / 0.0458 [4/5][1050/1583] Loss_D: 0.5057 Loss_G: 3.2545 D(x): 0.8705 D(G(z)): 0.2691 / 0.0546 [4/5][1100/1583] Loss_D: 0.4552 Loss_G: 2.0632 D(x): 0.7887 D(G(z)): 0.1704 / 0.1524 [4/5][1150/1583] Loss_D: 0.9933 Loss_G: 1.0264 D(x): 0.4507 D(G(z)): 0.0636 / 0.4182 [4/5][1200/1583] Loss_D: 0.5037 Loss_G: 1.9940 D(x): 0.6967 D(G(z)): 0.0959 / 0.1698 [4/5][1250/1583] Loss_D: 0.4760 Loss_G: 2.5973 D(x): 0.8192 D(G(z)): 0.2164 / 0.0945 [4/5][1300/1583] Loss_D: 1.0137 Loss_G: 3.8782 D(x): 0.9330 D(G(z)): 0.5405 / 0.0309 [4/5][1350/1583] Loss_D: 0.9084 Loss_G: 3.1406 D(x): 0.7540 D(G(z)): 0.3980 / 0.0648 [4/5][1400/1583] Loss_D: 0.6724 Loss_G: 4.1269 D(x): 0.9536 D(G(z)): 0.4234 / 0.0236 [4/5][1450/1583] Loss_D: 0.6452 Loss_G: 3.5163 D(x): 0.8730 D(G(z)): 0.3555 / 0.0412 [4/5][1500/1583] Loss_D: 0.8843 Loss_G: 1.4950 D(x): 0.5314 D(G(z)): 0.1035 / 0.2835 [4/5][1550/1583] Loss_D: 2.3345 Loss_G: 1.0675 D(x): 0.1448 D(G(z)): 0.0228 / 0.4177 .. GENERATED FROM PYTHON SOURCE LINES 657-670 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. .. GENERATED FROM PYTHON SOURCE LINES 670-681 .. code-block:: default 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() .. image-sg:: /beginner/images/sphx_glr_dcgan_faces_tutorial_002.png :alt: Generator and Discriminator Loss During Training :srcset: /beginner/images/sphx_glr_dcgan_faces_tutorial_002.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 682-689 **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. .. GENERATED FROM PYTHON SOURCE LINES 691-699 .. code-block:: default 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()) .. image-sg:: /beginner/images/sphx_glr_dcgan_faces_tutorial_003.png :alt: dcgan faces tutorial :srcset: /beginner/images/sphx_glr_dcgan_faces_tutorial_003.png :class: sphx-glr-single-img .. raw:: html


.. GENERATED FROM PYTHON SOURCE LINES 700-705 **Real Images vs. Fake Images** Finally, lets take a look at some real images and fake images side by side. .. GENERATED FROM PYTHON SOURCE LINES 705-724 .. code-block:: default # 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() .. image-sg:: /beginner/images/sphx_glr_dcgan_faces_tutorial_004.png :alt: Real Images, Fake Images :srcset: /beginner/images/sphx_glr_dcgan_faces_tutorial_004.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 725-739 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 `__ .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 6 minutes 59.778 seconds) .. _sphx_glr_download_beginner_dcgan_faces_tutorial.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: dcgan_faces_tutorial.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: dcgan_faces_tutorial.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_