A GAN helps a computer learn to create new things, like pictures, by playing a game between two parts: one makes fake things, the other checks if they are real or fake.
GAN concept (generator and discriminator) in TensorFlow
import tensorflow as tf from tensorflow.keras import layers # Generator model def make_generator_model(): model = tf.keras.Sequential([ layers.Dense(7*7*256, use_bias=False, input_shape=(100,)), layers.BatchNormalization(), layers.LeakyReLU(), layers.Reshape((7, 7, 256)), layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False), layers.BatchNormalization(), layers.LeakyReLU(), layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False), layers.BatchNormalization(), layers.LeakyReLU(), layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh') ]) return model # Discriminator model def make_discriminator_model(): model = tf.keras.Sequential([ layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same', input_shape=[28, 28, 1]), layers.LeakyReLU(), layers.Dropout(0.3), layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'), layers.LeakyReLU(), layers.Dropout(0.3), layers.Flatten(), layers.Dense(1) ]) return model
The generator tries to create fake data from random noise.
The discriminator tries to tell if data is real or fake.
generator = make_generator_model() noise = tf.random.normal([1, 100]) fake_image = generator(noise, training=False)
discriminator = make_discriminator_model() decision = discriminator(fake_image)
This program builds a simple GAN generator and discriminator. It creates one fake image from random noise and then checks what the discriminator thinks about it.
import tensorflow as tf from tensorflow.keras import layers import numpy as np # Generator model def make_generator_model(): model = tf.keras.Sequential([ layers.Dense(7*7*256, use_bias=False, input_shape=(100,)), layers.BatchNormalization(), layers.LeakyReLU(), layers.Reshape((7, 7, 256)), layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False), layers.BatchNormalization(), layers.LeakyReLU(), layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False), layers.BatchNormalization(), layers.LeakyReLU(), layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh') ]) return model # Discriminator model def make_discriminator_model(): model = tf.keras.Sequential([ layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same', input_shape=[28, 28, 1]), layers.LeakyReLU(), layers.Dropout(0.3), layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'), layers.LeakyReLU(), layers.Dropout(0.3), layers.Flatten(), layers.Dense(1) ]) return model # Create models generator = make_generator_model() discriminator = make_discriminator_model() # Create random noise noise = tf.random.normal([1, 100]) # Generate fake image fake_image = generator(noise, training=False) # Discriminator output decision = discriminator(fake_image) print(f"Fake image shape: {fake_image.shape}") print(f"Discriminator output: {decision.numpy()}")
The generator learns to make better fake images by trying to fool the discriminator.
The discriminator learns to get better at spotting fake images.
Training a GAN means both parts improve by playing against each other.
A GAN has two parts: generator (makes fake data) and discriminator (checks real or fake).
They learn together by competing, helping the generator create realistic data.
This idea is useful for creating new images, sounds, or data that look real.
Practice
What is the main role of the generator in a GAN?
Solution
Step 1: Understand the generator's purpose
The generator's job is to produce new data that mimics real data.Step 2: Differentiate from discriminator
The discriminator checks data authenticity, but the generator creates fake data.Final Answer:
To create fake data that looks real -> Option BQuick Check:
Generator = create fake data [OK]
- Confusing generator with discriminator
- Thinking generator labels data
- Assuming generator reduces data size
Which of the following is the correct way to define a simple generator model in TensorFlow Keras?
def make_generator_model():
model = tf.keras.Sequential([
tf.keras.layers.Dense(7*7*256, use_bias=False, input_shape=(100,)),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.LeakyReLU(),
tf.keras.layers.Reshape((7, 7, 256)),
tf.keras.layers.Conv2DTranspose(128, 5, strides=1, padding='same', use_bias=False),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.LeakyReLU(),
tf.keras.layers.Conv2DTranspose(1, 5, strides=2, padding='same', activation='tanh')
])
return model
Solution
Step 1: Check model layers and input
The model starts with a Dense layer with input_shape=(100,), which is correct for noise input.Step 2: Verify output activation and structure
The last Conv2DTranspose uses 'tanh' activation, common for generator output scaled between -1 and 1.Final Answer:
The code correctly defines a generator model -> Option CQuick Check:
Generator model code is correct [OK]
- Forgetting input_shape in first layer
- Using wrong activation for output layer
- Enabling bias unnecessarily in Dense layer
Given the following code snippet for a discriminator model, what will be the output shape after the last Conv2D layer?
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(64, 5, strides=2, padding='same', input_shape=(28, 28, 1)),
tf.keras.layers.LeakyReLU(),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.Conv2D(128, 5, strides=2, padding='same'),
tf.keras.layers.LeakyReLU(),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(1)
])
Solution
Step 1: Calculate output after first Conv2D
Input is (28,28,1), stride=2, padding='same' halves spatial dims: (14,14,64).Step 2: Calculate output after second Conv2D
Again stride=2, padding='same' halves spatial dims: (7,7,128).Final Answer:
(7, 7, 128) -> Option AQuick Check:
Conv2D output shape = (7,7,128) [OK]
- Forgetting padding='same' keeps output size rounded up
- Misapplying stride effect on dimensions
- Confusing number of filters with spatial size
Identify the error in this GAN training step code snippet:
noise = tf.random.normal([batch_size, noise_dim])
generated_images = generator(noise, training=True)
real_output = discriminator(real_images, training=True)
fake_output = discriminator(generated_images, training=False)
loss = generator_loss(fake_output) + discriminator_loss(real_output, fake_output)
Solution
Step 1: Check discriminator training mode
Discriminator must be in training mode for both real and fake images to update weights properly.Step 2: Identify incorrect training flag
Here, discriminator(fake images) uses training=False, which disables training behavior like dropout.Final Answer:
Discriminator should be in training mode for fake images -> Option AQuick Check:
Discriminator training mode = True for all inputs [OK]
- Setting discriminator training=False on fake data
- Confusing generator training flag
- Incorrect noise shape assumptions
You want to improve a GAN to generate clearer images. Which combined approach is best?
- Increase generator depth and add batch normalization
- Use a weaker discriminator to avoid overpowering generator
- Train discriminator more times per generator update
- Remove dropout layers from discriminator
Solution
Step 1: Evaluate option 1
Increasing generator depth and adding batch normalization helps create clearer, stable images.Step 2: Evaluate option 3
Training discriminator more per generator update helps discriminator learn better, pushing generator to improve.Step 3: Assess options 2 and 4
Weaker discriminator or removing dropout can reduce training quality and cause poor results.Final Answer:
Options 1 and 3 together are best -> Option DQuick Check:
Improve generator + stronger discriminator training = better images [OK]
- Weakening discriminator hurts GAN balance
- Removing dropout may cause overfitting
- Ignoring batch normalization benefits
Ready to prove it?
Pass the test and this pattern moves unknown
