AI Logic

Architectures

DCGAN

Updated:

Structure of DCGAN. Left: the generator, which projects 100-dimensional noise z to 4×4×1024 and turns it into a 64×64×3 image with four 5×5, stride-2 transposed convolutions. Right: the design guidelines for the discriminator, which stacks strided convolutions and outputs the probability that the input is real

Background and overview

DCGAN (Deep Convolutional GAN) builds the generator and discriminator of a GAN as convolutional networks that follow rules designed for stable training. Pooling and fully connected hidden layers are removed and replaced by strided convolutions, and it uses batch normalization, with ReLU in the generator and Leaky ReLU in the discriminator.

It was proposed in 2015 by Radford, Metz, and Chintala in the paper "Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks."

The original GAN was built from fully connected networks (multilayer perceptrons). There had been earlier attempts to use CNNs, which were successful in image classification, in GANs, but training was unstable and they did not work well. The authors of the DCGAN paper hit the same wall when they used CNN architectures common in classification directly in a GAN. They therefore explored architectures extensively and found architectural rules that train stably across a range of datasets and allow higher-resolution, deeper generators.

The paper's main contributions are the following four:

  • It presented architectural rules for stable training (next section).
  • It used the trained discriminator as a feature extractor, achieving image classification accuracy competitive with other unsupervised methods.
  • It visualized the discriminator's filters and showed that specific filters respond to specific objects (such as beds and windows).
  • It showed that adding and subtracting generator inputs z\boldsymbol{z} can manipulate the semantics of the generated images (expression, pose, and so on).

Architecture

DCGAN is trained in the same way as the original GAN, updating the generator and discriminator alternately. What differs is the architecture of the two networks. The paper summarizes the following 5 rules (Section 3).

RuleGeneratorDiscriminator
Remove poolingUpsample with fractionally strided convolutions (transposed convolutions)Downsample with strided convolutions
Batch normalizationApplied except at the output layerApplied except at the input layer
Remove fully connected hidden layersProject the input z\boldsymbol{z} with a matrix multiplication, reshape it into a 4D tensor, and feed it to the convolutionsFlatten the last convolutional layer and feed it into a single sigmoid output
Activation functionTanh at the output layer, ReLU elsewhereLeaky ReLU in all layers

Generator architecture

Figure 1 of the paper shows the generator used for LSUN (bedroom images) (left of the figure at the top of the article). An image is produced in the following order:

  1. Draw noise z\boldsymbol{z} from a 100-dimensional uniform distribution.
  2. Multiply z\boldsymbol{z} by a matrix (projection) and reshape the result into a 4×4×10244 \times 4 \times 1024 tensor.
  3. Apply four 5×55 \times 5, stride-2 transposed convolutions, doubling the height and width each time while reducing the channels: 8×8×5128 \times 8 \times 512 → 16×16×25616 \times 16 \times 256 → 32×32×12832 \times 32 \times 128 → 64×64×364 \times 64 \times 3.
  4. Apply Tanh to the output of the last layer to bring pixel values into −1-1 to 11. This is the generated image G(z)G(\boldsymbol{z}).

No fully connected layers or pooling are used anywhere. The initial projection is a matrix multiplication and could be called a fully connected layer, but its result is immediately reshaped into a 4D tensor and becomes the first input to the convolutions.

The caption of Figure 1 in the paper notes that calling fractionally strided convolutions "deconvolutions" is a misnomer. This operation is not the inverse of convolution; it spreads out the input and then convolves it. Today it is commonly called a "transposed convolution."

Discriminator architecture

The discriminator extracts features while shrinking the image with strided convolutions, flattens the last convolutional layer, and outputs the probability of being real through a single sigmoid output (right of the figure at the top of the article). The paper does not provide a layer-by-layer figure like that of the generator, but the description of the CIFAR-10 experiment shows that the top layer of the discriminator trained on ImageNet-1k had 512 channels.

Training setup

All models are trained with the same settings (Section 4).

ItemValue
PreprocessingOnly scaling pixels to the Tanh range [−1,1][-1, 1]
OptimizationAdam (learning rate 0.0002, β1=0.5\beta_1 = 0.5)
Batch size128
Weight initializationNormal distribution with mean 0 and standard deviation 0.02
Leaky ReLU slope0.2
Data augmentationNone

Training did not work well with Adam's recommended values. According to the paper, a learning rate of 0.001 was too high, and β1=0.9\beta_1 = 0.9 caused training to oscillate and become unstable. Lowering the learning rate to 0.0002 and β1\beta_1 to 0.5 stabilized it.

Why training is stable

The paper explains the reasons for choosing each rule as follows (Section 3):

  • Strided convolutions: instead of a fixed downsampling such as max pooling, the network learns its own downsampling (upsampling in the generator). This adopts the idea of the all convolutional net.
  • Removing fully connected layers: in classification models, there was a trend of replacing fully connected layers on top of convolutions with global average pooling. Global average pooling increased stability but slowed convergence. As a middle ground, the highest convolutional features are connected directly to the generator's input and the discriminator's output.
  • Batch normalization: it normalizes the input to each unit to zero mean and unit variance, reducing training problems caused by poor initialization and helping gradients flow in deep models. The paper says it was critical for getting deep generators to begin learning. It prevented a common GAN failure: the generator collapsing all samples to a single point.
  • Leaving some layers without batch normalization: applying batch normalization to all layers caused sample oscillation and model instability. This was avoided by not applying it to the generator's output layer and the discriminator's input layer.
  • Tanh at the generator output: using a bounded activation let the model learn more quickly to cover the color space of the training data.
  • Leaky ReLU in the discriminator: it worked well, especially at higher resolutions. The original GAN's discriminator used Maxout.

As an everyday analogy, DCGAN keeps the idea of the original GAN (a contest between a counterfeiter and the police) unchanged, but gives the two "tools suited to handling images" and "rules that prevent things from spiraling out of control."

Experimental results

The paper trained DCGAN on LSUN bedrooms (just over 3 million images), ImageNet-1k (downscaled to 32×3232 \times 32 with center crops), and face images collected from the web (about 350,000 face regions).

Classifying CIFAR-10 with discriminator features

Features from all convolutional layers of the discriminator trained on ImageNet-1k were each max-pooled to 4×44 \times 4 and concatenated (28672 dimensions), and a linear SVM classified CIFAR-10. Because DCGAN was not trained on CIFAR-10, this also tests robustness to a different dataset (accuracy %).

ModelAccuracyAccuracy (400 per class)Max number of feature units
1-layer K-means80.663.7 (±0.7)4800
3-layer K-means (learned receptive field)82.070.7 (±0.7)3200
View-invariant K-means81.972.6 (±0.7)6400
Exemplar CNN84.377.4 (±0.2)1024
DCGAN + L2-SVM82.873.8 (±0.4)512

DCGAN outperformed all the K-means-based methods but fell short of Exemplar CNN.

Classifying SVHN with discriminator features (1000 labels)

On SVHN, a dataset of house number digits, classification was done in the same way using only 1000 labeled images (error rate %).

ModelError rate
KNN77.93
TSVM66.55
M1 + M236.02
SWWAE (with dropout)23.56
DCGAN + L2-SVM22.48
CNN with the same architecture, purely supervised28.87 (validation)

This was the state of the art at the time for classification with 1000 labels. Because a CNN with the same architecture trained purely supervised reached 28.87%, the paper argues that the good result comes not from the architecture itself but from the features learned by the GAN.

Investigating the inside of the generator

  • Walking in the latent space: moving smoothly between two points in z\boldsymbol{z} changed the image semantics smoothly, for example a room without windows gradually turning into a room with a large window. The absence of sharp transitions suggests that the model has not memorized the training data.
  • Forgetting to draw windows: 52 window bounding boxes were drawn by hand on 150 samples to identify the feature maps that respond to windows (about 200). When these were removed during generation, the generator mostly stopped drawing windows and replaced them with other objects such as doors and mirrors.
  • Vector arithmetic: computing z\boldsymbol{z} as "smiling woman" − "neutral woman" + "neutral man" generated a "smiling man." Using a single z\boldsymbol{z} per concept was unstable, but averaging the z\boldsymbol{z} of 3 samples made it stable. Doing the same arithmetic in pixel space only produced misaligned, overlapping images. Face pose could also be changed linearly in z\boldsymbol{z} space.

To remove near-duplicate images from the LSUN training data, the paper created codes with a 30723072-128128-30723072 denoising autoencoder and treated images with matching binarized codes as duplicates. About 275,000 duplicates were removed this way.

Practical notes

When using DCGAN, keep the following points in mind:

  • Some instability remains in long training: the paper reports that when training continues for a long time, a subset of filters can collapse into a single oscillating mode. Check generated samples during training and stop at a good point.
  • Respect which layers get batch normalization: do not apply it to the generator's output layer or the discriminator's input layer. Applying it to all layers makes training unstable.
  • Match the ranges of training data and output: since the generator output is Tanh, scale the training data pixels to [−1,1][-1, 1] as well.
  • Match Adam's settings to the paper: a learning rate of 0.0002 and β1=0.5\beta_1 = 0.5 are the starting point.
  • Do not use log-likelihood for evaluation: the paper does not use it, considering log-likelihood a poor metric for evaluating generative models. Today, FID and the Inception Score are commonly used.

To exactly double the height and width with a 5×55 \times 5, stride-2 layer using PyTorch's nn.ConvTranspose2d, specify padding=2, output_padding=1. Without them, the output size will not be 2H2H (with padding=0, it is 2H+32H + 3). Also, since the model contains batch normalization, switch to G.eval() when generating so that it uses the running averages rather than training-time statistics.

Comparison with other methods

The original GAN and DCGAN are compared from the same angles.

AspectGAN (2014)DCGAN (2015)
GeneratorMultilayer perceptron (ReLU and sigmoid)Transposed convolutions (ReLU, Tanh output)
DiscriminatorMultilayer perceptron (Maxout, dropout)Strided convolutions (Leaky ReLU)
NormalizationNoneBatch normalization (except the generator's output layer and the discriminator's input layer)
OptimizationGradient descent with momentumAdam (learning rate 0.0002, β1=0.5\beta_1 = 0.5)
Images in experimentsMNIST, TFD, CIFAR-10LSUN bedrooms, ImageNet-1k, faces (up to 64×6464 \times 64)
Use of learned featuresNot evaluatedClassifying CIFAR-10 and SVHN with discriminator features

Rough guidelines for choosing:

  • Trying out or learning how GANs work on images: DCGAN has a simple architecture and clear rules, making it a good first image GAN to implement.
  • More stable training or higher image quality is needed: successors built on the DCGAN architecture are used, such as WGAN with a different loss, methods that normalize the discriminator with Spectral Normalization, and StyleGAN.
  • A mapping into the latent space or a lower bound on the likelihood is also wanted: VAE is a candidate.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
DCGAN of Radford et al. (2015) (64×64 color images)
- Generator: z (100-dim) -> project to 4×4×1024 -> four 5×5, stride-2 transposed convolutions -> 64×64×3 (Figure 1)
- Discriminator: strided convolutions (the paper gives no layer-by-layer figure; the channels 64->128->256->512 are chosen for this example)
- Init N(0, 0.02), Adam(lr=0.0002, beta1=0.5), LeakyReLU slope 0.2, batch size 128 (Section 4)
"""

z_dim = 100


def up(cin, cout):
  # exactly double height and width with a 5×5, stride-2 transposed convolution (padding=2, output_padding=1)
  return nn.ConvTranspose2d(cin, cout, 5, stride=2, padding=2, output_padding=1, bias=False)


def down(cin, cout):
  # halve height and width with a 5×5, stride-2 convolution (no pooling)
  return nn.Conv2d(cin, cout, 5, stride=2, padding=2, bias=False)


class Generator(nn.Module):
  def __init__(self):
    super().__init__()
    self.project = nn.Linear(z_dim, 4 * 4 * 1024, bias=False)   # projection (matrix multiplication)
    self.bn0 = nn.BatchNorm2d(1024)
    self.net = nn.Sequential(
      up(1024, 512), nn.BatchNorm2d(512), nn.ReLU(True),   # 8×8×512
      up(512, 256), nn.BatchNorm2d(256), nn.ReLU(True),    # 16×16×256
      up(256, 128), nn.BatchNorm2d(128), nn.ReLU(True),    # 32×32×128
      up(128, 3), nn.Tanh(),                               # 64×64×3. Output layer: no batch norm, Tanh
    )

  def forward(self, z):
    h = self.project(z).view(-1, 1024, 4, 4)               # reshape into a 4D tensor
    return self.net(torch.relu(self.bn0(h)))


class Discriminator(nn.Module):
  def __init__(self):
    super().__init__()
    self.net = nn.Sequential(
      down(3, 64), nn.LeakyReLU(0.2, True),                          # no batch norm on the input layer. 32×32
      down(64, 128), nn.BatchNorm2d(128), nn.LeakyReLU(0.2, True),   # 16×16
      down(128, 256), nn.BatchNorm2d(256), nn.LeakyReLU(0.2, True),  # 8×8
      down(256, 512), nn.BatchNorm2d(512), nn.LeakyReLU(0.2, True),  # 4×4
      nn.Flatten(),
      nn.Linear(4 * 4 * 512, 1),                          # single output (the sigmoid is computed inside the loss)
    )

  def forward(self, x):
    return self.net(x)


def init_weights(m):
  # initialize all weights from a normal distribution with mean 0 and std 0.02
  if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d, nn.Linear)):
    nn.init.normal_(m.weight, 0.0, 0.02)
  elif isinstance(m, nn.BatchNorm2d):
    nn.init.normal_(m.weight, 1.0, 0.02)
    nn.init.zeros_(m.bias)


device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
G, D = Generator().to(device), Discriminator().to(device)
G.apply(init_weights)
D.apply(init_weights)

bce = nn.BCEWithLogitsLoss()
opt_g = torch.optim.Adam(G.parameters(), lr=2e-4, betas=(0.5, 0.999))
opt_d = torch.optim.Adam(D.parameters(), lr=2e-4, betas=(0.5, 0.999))


def sample_z(m):
  # uniform noise (the range -1 to 1 is chosen for this example)
  return torch.rand(m, z_dim, device=device) * 2 - 1


def train_step(x):
  """x: [128, 3, 64, 64], pixels scaled to -1 to 1"""
  m = x.size(0)
  ones = torch.ones(m, 1, device=device)
  zeros = torch.zeros(m, 1, device=device)

  # discriminator: 1 for real, 0 for fake (no gradient flows into the generator)
  fake = G(sample_z(m)).detach()
  loss_d = bce(D(x), ones) + bce(D(fake), zeros)
  opt_d.zero_grad()
  loss_d.backward()
  opt_d.step()

  # generator: make the discriminator judge "real" (maximize log D(G(z)))
  loss_g = bce(D(G(sample_z(m))), ones)
  opt_g.zero_grad()
  loss_g.backward()
  opt_g.step()
  return loss_d.item(), loss_g.item()


# usage: call G.train(); D.train(), then train_step(x.to(device)) for each batch from the data loader
# when generating, switch batch norm to running averages
G.eval()
with torch.no_grad():
  images = G(sample_z(64))        # [64, 3, 64, 64], -1 to 1

FAQ

Q. What is the difference between DCGAN and the original GAN?
A.

The training method (a minimax game that updates the generator and discriminator alternately) is the same. The difference is the network architecture: the original GAN mainly used multilayer perceptrons, whereas DCGAN is built only from convolutions, removes pooling and fully connected hidden layers, and adds batch normalization. Following these rules made it possible to train image GANs stably on a range of datasets.

Q. Why is batch normalization not applied to the generator's output layer and the discriminator's input layer?
A.

According to the paper, applying batch normalization to all layers made the generated samples oscillate and the model unstable. Excluding only the generator's output layer and the discriminator's input layer avoided this problem. Meanwhile, batch normalization in the other layers was essential for deep generators to begin learning, and it also prevented the failure in which all samples collapse to a single point.

Q. What is the "transposed convolution" in the DCGAN generator?
A.

It is a convolution that enlarges the height and width, the opposite of a strided convolution. The paper calls it a "fractionally strided convolution" and notes that calling it a "deconvolution" is a misnomer. The DCGAN generator uses 5×55 \times 5, stride-2 transposed convolutions to double the height and width step by step from 4×44 \times 4 to 64×6464 \times 64. See transposed convolution for details.

References

  1. Radford, A., Metz, L., & Chintala, S. (2015). Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks. arXiv:1511.06434(ICLR 2016).
  2. Goodfellow, I. J., et al. (2014). Generative Adversarial Nets. NeurIPS 2014. arXiv:1406.2661.