Overview

6 CycleGAN: Converting Blond Hair to Black Hair

This chapter introduces CycleGAN as a practical solution for unpaired image-to-image translation, using the task of converting blond hair to black hair and vice versa as a running example. Unlike earlier GAN variants that simply learn to generate realistic images, CycleGAN learns mappings between two visual domains without requiring paired examples. The key idea is cycle consistency: an image translated to the other domain should be able to return to its original form with minimal change. This capability enables a wide range of applications, from hair color editing and adding/removing eyeglasses to style transfer and cross-modality medical imaging.

The model architecture consists of two generators and two discriminators that translate images in both directions between domains. Training uses unpaired datasets and optimizes a composite objective: adversarial losses encourage outputs that look real to their target-domain discriminators, while cycle consistency loss (pixel-wise L1) penalizes discrepancies between original images and their round-trip reconstructions. The chapter builds a general PyTorch pipeline for two-domain datasets, demonstrating data preparation with resizing, normalization to the [-1, 1] range, and simple yet effective augmentations like horizontal flips. For the hair-color task, large subsets of celebrity faces with black and blond hair are assembled to support robust, data-rich training.

Implementation details include PatchGAN-style discriminators with reflection padding and sigmoid outputs, and generators that downsample, pass through nine residual blocks to stabilize deep training, then upsample and emit images via a tanh output. The adversarial term is measured with mean squared error, the cycle term with mean absolute error (weighted higher, e.g., by 10), and optimization uses Adam with standard GAN betas alongside automatic mixed precision for speed. The training loop jointly updates discriminators and generators, periodically saving sample translations for visual monitoring, and ultimately retains only the generators for inference. Results show high-fidelity, bidirectional hair-color translation and strong round-trip consistency, and the same framework readily generalizes to other two-domain tasks such as adding or removing eyeglasses.

The architecture of A CycleGAN to convert images with black hair to ones with blond hair and to convert images with blond hair to ones with black hair. The diagram also outlines the training steps to minimize adversarial losses. How the model minimizes cycle consistency losses is explained in figure 6.2.
How CycleGAN minimizes cycle consistency losses between original black hair images and fake ones after roundtrips and cycle consistency losses between original blond hair images and fake ones after roundtrips.
Sample images of celebrity faces with black or blond hair.
The architecture of a residual block. The input x is passed through a series of transformations (two sets of Conv2d layer & InstanceNorm2d layer, and a ReLU activation). The input x is then added back to the output of these transformations, f(x). The output of the residual block is therefore x+f(x).
A roundtrip conversion of images with black hair. Images in the top row are the original images with black hair from the training set. Images in the middle row are the corresponding fake images with blond hair, produced by the trained blond hair generator. Images in the bottom row are fake images with black hair after a roundtrip: we feed the images in the middle row to the trained black hair generator to create fake images with black hair.
A roundtrip conversion of images with blond hair. Images in the top row are the original images with blond hair from the training set. Images in the middle row are the corresponding fake images with black hair, produced by the trained black hair generator. Images in the bottom row are fake images with blond hair after a roundtrip conversion: we feed the images in the middle row to the trained blond hair generator to create fake images with blond hair.

Summary

  • CycleGAN can translate images between two domains without paired examples. It consists of two discriminators and two generators. One generator converts images in domain A to domain B while the other generator converts images in domain B to domain A. The two discriminators classify if a given image is from a specific domain.
  • CycleGAN uses a cycle consistency loss function to ensure the original image can be reconstructed from the transformed image, encouraging the preservation of key features.
  • A properly constructed CycleGAN model can be applied to any dataset with images from two domains. The same model can be trained with different datasets and be used to translate images in different domains.
  • When we have abundant high-quality training data, the trained CycleGAN can convert images in one domain to another and convert them back to the original domain. The images after a roundtrip conversion can potentially look almost identical to the original images.

FAQ

What is CycleGAN and how does it differ from standard GANs?CycleGAN performs unpaired image-to-image translation between two domains using two generators and two discriminators. Unlike standard GANs that generate images from noise and often require paired data for translation tasks, CycleGAN learns mappings A→B and B→A without paired examples and enforces that translating there and back reconstructs the original image.
What is cycle consistency loss and why is it important?Cycle consistency loss measures how close an original image is to its roundtrip reconstruction (A→B→A and B→A→B). It is computed as the pixel-wise L1 loss between the original and the reconstructed image in each domain and summed across both domains. This encourages the model to preserve key content while changing only domain-specific attributes (e.g., hair color).
Why does CycleGAN not need paired training data?Because the cycle consistency constraint ties each mapping to its inverse (A→B→A and B→A→B), the model can learn domain-to-domain transformations using separate unpaired sets from each domain. The discriminators ensure realism in each target domain, while cycle loss enforces content preservation without requiring one-to-one aligned pairs.
How are the two generators and two discriminators used for hair color translation?One generator translates black→blond and the other blond→black. Each domain has its own discriminator that judges whether images in that domain are real or generated. Domains are symmetric; calling one “A” and the other “B” is arbitrary.
What datasets are used and how are they prepared?The chapter uses unpaired celebrity face images filtered from CelebA into black-hair and blond-hair subsets (tens of thousands of images each). Images are selected via the attribute CSV and moved into separate folders for the two domains; no pairing between specific black/blond images is required.
How are images preprocessed and why is the batch size set to 1?Images are resized to 256×256, normalized to [-1, 1], and augmented with random horizontal flipping using albumentations. A batch size of 1 is used due to the memory footprint and because translations use paired samples drawn independently from each domain per iteration.
What do the generator and discriminator architectures look like?The generator uses reflect-padded convolutions, instance normalization, ReLU activations, two downsampling blocks, nine residual blocks, two upsampling blocks, and a tanh output. The discriminator stacks reflect-padded Conv2d layers with LeakyReLU and ends with a sigmoid to output a real/fake probability for the target domain.
Which loss functions are used and how are they combined?Adversarial losses use MSE (L2) against ones/zeros for each domain’s discriminator output. Cycle consistency uses L1 between original and roundtrip images. The total generator loss is adv_A + adv_B + 10 × (cycle_A + cycle_B). The discriminator loss averages the adversarial losses from both discriminators.
How is training implemented and accelerated?Training uses Adam (lr=1e-5, betas=(0.5, 0.999)) for both generators and discriminators, PyTorch AMP (torch.cuda.amp) for mixed-precision speedups, and detach() on fakes when updating discriminators. Progress is monitored by periodically saving real and generated images. Training takes hours on GPU and can take much longer on CPU.
How do I evaluate results and apply the model to other domains?Evaluate by visual inspection of A→B, B→A, and roundtrips A→B→A, B→A→B; good models reconstruct originals closely after roundtrips. The same pipeline is domain-agnostic: swap A/B if desired and apply to other two-domain tasks (e.g., adding/removing eyeglasses). After training, keep the generators for inference and discard the discriminators.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Learn Generative AI with PyTorch ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Learn Generative AI with PyTorch ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Learn Generative AI with PyTorch ebook for free