Generative Adversarial Networks (GAN)

Deep Learning with Keras and TensorFlow 13 min min read Updated: Nov 16, 2026 Advanced
Generative Adversarial Networks (GAN)
Advanced Topic 4 of 7

The Idea of a GAN

A GAN has two networks that play a game against each other.

NetworkRole
GeneratorCreates fake images from random noise
DiscriminatorLooks at an image and decides: real or fake?
Simple example: A counterfeiter (generator) prints fake money. A police officer (discriminator) tries to spot the fakes. Each time the officer catches a fake, the counterfeiter improves. After a long time the fakes are so good that the officer cannot tell the difference.

Step 1: Load and Prepare Data

python import tensorflow as tf import keras from keras import layers import numpy as np (x_train, _), _ = keras.datasets.mnist.load_data() x_train = x_train.reshape(-1, 28, 28, 1).astype("float32") x_train = (x_train - 127.5) / 127.5 # scale to -1..1 (tanh output) dataset = tf.data.Dataset.from_tensor_slices(x_train).shuffle(60000).batch(128)

Step 2: Generator

python latent_dim = 100 generator = keras.Sequential([ keras.Input(shape=(latent_dim,)), layers.Dense(7 * 7 * 128), layers.Reshape((7, 7, 128)), layers.BatchNormalization(), layers.LeakyReLU(0.2), layers.Conv2DTranspose(64, 4, strides=2, padding="same"), # 14 x 14 layers.BatchNormalization(), layers.LeakyReLU(0.2), layers.Conv2DTranspose(1, 4, strides=2, padding="same", activation="tanh"), # 28 x 28 ], name="generator")

Step 3: Discriminator

python discriminator = keras.Sequential([ keras.Input(shape=(28, 28, 1)), layers.Conv2D(64, 4, strides=2, padding="same"), layers.LeakyReLU(0.2), layers.Dropout(0.3), layers.Conv2D(128, 4, strides=2, padding="same"), layers.LeakyReLU(0.2), layers.Dropout(0.3), layers.Flatten(), layers.Dense(1), # one score: real or fake (logit) ], name="discriminator")

Step 4: The Training Step

python bce = keras.losses.BinaryCrossentropy(from_logits=True) g_opt = keras.optimizers.Adam(2e-4, beta_1=0.5) d_opt = keras.optimizers.Adam(2e-4, beta_1=0.5) @tf.function def train_step(real_images): batch = tf.shape(real_images)[0] noise = tf.random.normal((batch, latent_dim)) with tf.GradientTape() as g_tape, tf.GradientTape() as d_tape: fake_images = generator(noise, training=True) real_out = discriminator(real_images, training=True) fake_out = discriminator(fake_images, training=True) # discriminator: real -> 1, fake -> 0 d_loss = bce(tf.ones_like(real_out), real_out) + bce(tf.zeros_like(fake_out), fake_out) # generator: wants the discriminator to say 1 for fakes g_loss = bce(tf.ones_like(fake_out), fake_out) d_grads = d_tape.gradient(d_loss, discriminator.trainable_variables) g_grads = g_tape.gradient(g_loss, generator.trainable_variables) d_opt.apply_gradients(zip(d_grads, discriminator.trainable_variables)) g_opt.apply_gradients(zip(g_grads, generator.trainable_variables)) return d_loss, g_loss

Step 5: Train and Look at Results

python import matplotlib.pyplot as plt fixed_noise = tf.random.normal((16, latent_dim)) def show(epoch): imgs = generator(fixed_noise, training=False).numpy() plt.figure(figsize=(4, 4)) for i in range(16): plt.subplot(4, 4, i + 1) plt.imshow(imgs[i, :, :, 0] * 0.5 + 0.5, cmap="gray") plt.axis("off") plt.suptitle(f"Epoch {epoch}") plt.show() for epoch in range(1, 31): for batch in dataset: d_loss, g_loss = train_step(batch) if epoch % 10 == 0: print(epoch, float(d_loss), float(g_loss)) show(epoch)

After a few epochs the images look like blurry blobs, and after about 30 epochs many of them look like real handwritten digits.

Common GAN Problems

ProblemMeaning
Mode collapseThe generator produces only a few kinds of images
Unstable trainingOne network becomes much stronger than the other
No clear stopping pointLoss values are hard to interpret, so look at the images
Tip: GANs need patience. Keep both learning rates small, use LeakyReLU and Adam with beta_1 = 0.5, and inspect generated images regularly.

Conclusion

GANs create new data by letting two networks compete. This custom loop approach is also the base for more advanced image generators.

Quick Summary: The generator tries to fool the discriminator, and the discriminator tries to catch fakes. Train them alternately.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators