Generation code of conditional GAN using tensorflow and keras
- User
Generation code of conditional GAN using tensorflow and keras
- Assistant
Generation code of conditional GAN using tensorflow and keras
A Conditional Generative Adversarial Network (cGAN) is an extension of the standard GAN that allows you to generate images conditioned on certain information, such as class labels. This means you can control the properties of the generated images by providing additional input to both the generator and discriminator.
In this example, we'll implement a cGAN using TensorFlow and Keras to generate handwritten digits conditioned on their class labels using the MNIST dataset.
Let's dive into the implementation step by step.
import tensorflow as tf
from tensorflow.keras import layers
import numpy as np
import matplotlib.pyplot as plt
We'll use the MNIST dataset and preprocess it to normalize the images and prepare the labels.
# Load the MNIST dataset
(train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()
# Normalize the images to [-1, 1] range
train_images = (train_images.astype(np.float32) - 127.5) / 127.5
train_images = np.expand_dims(train_images, axis=-1)
# Number of classes
num_classes = 10
# One-hot encode the labels
train_labels = tf.keras.utils.to_categorical(train_labels, num_classes)
The generator takes two inputs: random noise and the label (as a one-hot vector). It concatenates these inputs and generates an image corresponding to the input label.
def build_generator(latent_dim, num_classes):
label_input = layers.Input(shape=(num_classes,), name='generator_label_input')
noise_input = layers.Input(shape=(latent_dim,), name='generator_noise_input')
# Concatenate noise and label
x = layers.Concatenate()([noise_input, label_input])
x = layers.Dense(7 * 7 * 256, use_bias=False)(x)
x = layers.BatchNormalization()(x)
x = layers.LeakyReLU(alpha=0.2)(x)
x = layers.Reshape((7, 7, 256))(x) # 7x7x256
# Upsample to 14x14
x = layers.Conv2DTranspose(128, kernel_size=5, strides=1, padding='same', use_bias=False)(x)
x = layers.BatchNormalization()(x)
x = layers.LeakyReLU(alpha=0.2)(x)
# Upsample to 14x14
x = layers.Conv2DTranspose(128, kernel_size=5, strides=2, padding='same', use_bias=False)(x)
x = layers.BatchNormalization()(x)
x = layers.LeakyReLU(alpha=0.2)(x)
# Upsample to 28x28
x = layers.Conv2DTranspose(64, kernel_size=5, strides=2, padding='same', use_bias=False)(x)
x = layers.BatchNormalization()(x)
x = layers.LeakyReLU(alpha=0.2)(x)
# Final layer to get 28x28x1
x = layers.Conv2DTranspose(1, kernel_size=5, strides=1, padding='same', activation='tanh')(x)
generator = tf.keras.Model([noise_input, label_input], x, name='generator')
return generator
The discriminator takes two inputs: an image and a label. It concatenates the image and the label (after embedding the label into a spatial form) and then processes them to output a single scalar indicating real or fake.
def build_discriminator(img_shape, num_classes):
label_input = layers.Input(shape=(num_classes,), name='discriminator_label_input')
image_input = layers.Input(shape=img_shape, name='discriminator_image_input')
# Embed and reshape label to match image spatial dimensions
x_label = layers.Dense(img_shape[0] * img_shape[1], activation='relu')(label_input)
x_label = layers.Reshape((img_shape[0], img_shape[1], 1))(x_label)
# Concatenate image and label
x = layers.Concatenate(axis=-1)([image_input, x_label])
x = layers.Conv2D(64, kernel_size=5, strides=2, padding='same')(x)
x = layers.LeakyReLU(alpha=0.2)(x)
x = layers.Dropout(0.3)(x)
x = layers.Conv2D(128, kernel_size=5, strides=2, padding='same')(x)
x = layers.LeakyReLU(alpha=0.2)(x)
x = layers.Dropout(0.3)(x)
x = layers.Flatten()(x)
x = layers.Dense(1, activation='sigmoid')(x)
discriminator = tf.keras.Model([image_input, label_input], x, name='discriminator')
return discriminator
# Set random seed for reproducibility
tf.random.set_seed(42)
# Define input dimensions
latent_dim = 100
img_shape = train_images.shape[1:] # (28, 28, 1)
# Build models
generator = build_generator(latent_dim, num_classes)
discriminator = build_discriminator(img_shape, num_classes)
# Compile discriminator
discriminator.compile(
loss='binary_crossentropy',
optimizer=tf.keras.optimizers.Adam(learning_rate=0.0002, beta_1=0.5),
metrics=['accuracy']
)
# Freeze discriminator weights in the combined model
discriminator.trainable = False
# Build and compile the combined model
noise_input = layers.Input(shape=(latent_dim,))
label_input = layers.Input(shape=(num_classes,))
generated_image = generator([noise_input, label_input])
validity = discriminator([generated_image, label_input])
combined = tf.keras.Model([noise_input, label_input], validity)
combined.compile(
loss='binary_crossentropy',
optimizer=tf.keras.optimizers.Adam(learning_rate=0.0002, beta_1=0.5)
)
We'll define a training loop to train both the discriminator and generator iteratively.
import os
# Training parameters
epochs = 10000
batch_size = 64
sample_interval = 1000
# Labels for real and fake data
real = np.ones((batch_size, 1))
fake = np.zeros((batch_size, 1))
# Create directory to save generated images
os.makedirs('cgan_images', exist_ok=True)
for epoch in range(1, epochs + 1):
# ---------------------
# Train Discriminator
# ---------------------
# Select a random batch of real images and labels
idx = np.random.randint(0, train_images.shape[0], batch_size)
real_imgs = train_images[idx]
real_labels = train_labels[idx]
# Sample noise and generate a batch of new images
noise = np.random.normal(0, 1, (batch_size, latent_dim))
random_labels = np.random.randint(0, num_classes, batch_size)
random_labels_one_hot = tf.keras.utils.to_categorical(random_labels, num_classes)
gen_imgs = generator.predict([noise, random_labels_one_hot])
# Train the discriminator
d_loss_real = discriminator.train_on_batch([real_imgs, real_labels], real)
d_loss_fake = discriminator.train_on_batch([gen_imgs, random_labels_one_hot], fake)
d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)
# ---------------------
# Train Generator
# ---------------------
# Sample noise and labels
noise = np.random.normal(0, 1, (batch_size, latent_dim))
sampled_labels = np.random.randint(0, num_classes, batch_size)
sampled_labels_one_hot = tf.keras.utils.to_categorical(sampled_labels, num_classes)
# Train the generator (to have the discriminator label samples as real)
g_loss = combined.train_on_batch([noise, sampled_labels_one_hot], real)
# Print progress
if epoch % 100 == 0 or epoch == 1:
print(f"{epoch} [D loss: {d_loss[0]:.4f}, acc.: {100*d_loss[1]:.2f}%] [G loss: {g_loss:.4f}]")
# If at save interval, save generated image samples
if epoch % sample_interval == 0:
r, c = 2, 5
noise = np.random.normal(0, 1, (r * c, latent_dim))
sampled_labels = np.array([num for num in range(c) for _ in range(r)])
sampled_labels_one_hot = tf.keras.utils.to_categorical(sampled_labels, num_classes)
gen_imgs = generator.predict([noise, sampled_labels_one_hot])
# Rescale images 0 - 1
gen_imgs = 0.5 * gen_imgs + 0.5
fig, axs = plt.subplots(r, c, figsize=(c*2, r*2))
cnt = 0
for i in range(r):
for j in range(c):
axs[i,j].imshow(gen_imgs[cnt, :, :, 0], cmap='gray')
axs[i,j].set_title(f"Digit: {sampled_labels[cnt]}")
axs[i,j].axis('off')
cnt +=1
fig.savefig(f"cgan_images/mnist_{epoch}.png")
plt.close()
Training the Discriminator:
Training the Generator:
Saving Generated Images:
sample_interval), we generate and save a grid of images to visualize the generator's progress.After training, you should see generated images saved in the cgan_images directory at each sampling interval. These images should resemble handwritten digits corresponding to the conditioned labels.
Here's an example of how the generated images might look after training:
[image: Example Generated Images] open
Note: The actual output will be saved in your cgan_images directory.
This example demonstrates how to implement a Conditional GAN using TensorFlow and Keras to generate MNIST digits conditioned on class labels. cGANs are powerful for tasks where you want control over the generated outputs, such as image-to-image translation, text-to-image synthesis, and more.
Feel free to experiment with different architectures, datasets, and conditioning information to explore the versatility of conditional GANs!
Not yet included in a published release.