Assignment-10.1 NLP 2103a51375
Assignment-10.1 NLP 2103a51375
Generative models are a class of machine learning models that generate new data
instances that resemble your training data. These models can be used for various tasks,
such as creating realistic images, text, or even music. In this lab assignment, we'll focus on
implementing and training generative models, particularly a Variational Autoencoder
(VAE) and a Generative Adversarial Network (GAN), using a simple dataset like MNIST or a
text dataset for generating synthetic samples. [CO5]
(iii) Visualize the latent space and generated images to understand how well the model
captures the data distribution.
Ans:
A VAE consists of an encoder, a decoder, and a latent space. The encoder maps inputs to a
latent space distribution, and the decoder reconstructs the inputs from sampled points in the
latent space.
import numpy as np
import tensorflow as tf
# Hyperparameters
latent_dim = 2
input_dim = 28 * 28
# Encoder
inputs = Input(shape=(input_dim,))
h = Dense(512, activation='relu')(inputs)
z_mean = Dense(latent_dim)(h)
z_log_var = Dense(latent_dim)(h)
# Sampling function
def sampling(args):
z = Lambda(sampling)([z_mean, z_log_var])
# Decoder
h_decoded = decoder_h(z)
x_decoded_mean = decoder_mean(h_decoded)
# VAE model
vae.add_loss(vae_loss)
vae.compile(optimizer='adam')
vae.summary()
# Train VAE
decoder_input = Input(shape=(latent_dim,))
_h_decoded = decoder_h(decoder_input)
_x_decoded_mean = decoder_mean(_h_decoded)
x_test_encoded = encoder.predict(x_test)
plt.figure(figsize=(8, 6))
plt.colorbar()
plt.show()
generated_images = decoder.predict(random_latent_vectors)
plt.figure(figsize=(10, 2))
plt.subplot(1, 10, i + 1)
plt.axis("off")
plt.show()
GANs consist of a generator that learns to produce realistic data and a discriminator that
learns to distinguish real data from generated data.
# Hyperparameters
latent_dim = 100
# Generator
def build_generator():
model = tf.keras.Sequential([
Dense(256, input_dim=latent_dim),
LeakyReLU(alpha=0.2),
BatchNormalization(momentum=0.8),
Dense(512),
LeakyReLU(alpha=0.2),
BatchNormalization(momentum=0.8),
Dense(1024),
LeakyReLU(alpha=0.2),
BatchNormalization(momentum=0.8),
Reshape((28, 28))
])
return model
# Discriminator
def build_discriminator():
model = tf.keras.Sequential([
Flatten(input_shape=(28, 28)),
Dense(512),
LeakyReLU(alpha=0.2),
Dense(256),
LeakyReLU(alpha=0.2),
Dense(1, activation="sigmoid")
])
return model
# Compile GAN
generator = build_generator()
discriminator = build_discriminator()
discriminator.trainable = False
z = Input(shape=(latent_dim,))
generated_img = generator(z)
valid = discriminator(generated_img)
# Training Function
# Train discriminator
real_imgs = x_train[idx]
z = np.random.normal(size=(batch_size, latent_dim))
fake_imgs = generator.predict(z)
# Train generator
z = np.random.normal(size=(batch_size, latent_dim))
generate_and_save_images(epoch)
z = np.random.normal(size=(examples, latent_dim))
generated_images = generator.predict(z)
plt.figure(figsize=(10, 2))
for i in range(examples):
plt.subplot(1, examples, i + 1)
plt.axis("off")
plt.show()
# Train GAN
train_gan(epochs=10000, batch_size=64)
For VAE:
- The latent space scatter plot shows how inputs are mapped.
- Generated images can be visualized by sampling random points in the latent space.
For GAN:
- Generated images demonstrate how well the generator learns to mimic the dataset.
Next Steps
3. Experiment with larger latent dimensions and deeper networks for better generation
quality.