To improve and extend your Variational Autoencoder (VAE) to better handle more complex data, we'll follow the tasks outlined. We'll proceed step by step, implementing each task and explaining the changes. Here's how you can modify and extend your VAE:
1. Choosing a New Dataset
We'll use the Fashion MNIST dataset for this task. It contains 60,000 training images and 10,000 test images of clothing items, which are more complex than digits in MNIST.
Loading and Preprocessing Fashion MNIST
First, let's load the dataset and preprocess it similarly to how we did with MNIST:
import numpy as np
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Layer, Dense, Input, Flatten, Reshape, Conv2D, Conv2DTranspose, LeakyReLU
from tensorflow.keras.models import Model
from tensorflow.keras.datasets import fashion_mnist
# Load Fashion MNIST dataset
(x_train, _), (x_test, _) = fashion_mnist.load_data()
# Normalize the data to range [0, 1]
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
# Expand dimensions to include the channel dimension (since Fashion MNIST is grayscale, so channels=1)
x_train = np.expand_dims(x_train, -1) # shape: (60000, 28, 28, 1)
x_test = np.expand_dims(x_test, -1)
2. Modifying the VAE Architecture
Implementing a Convolutional VAE
To capture the spatial hierarchies in images, we'll use convolutional layers in both the encoder and decoder.
Encoder
The encoder will consist of convolutional layers that reduce the spatial dimensions while increasing the depth:
latent_dim = 16 # Dimension of the latent space
# Encoder
def build_encoder(input_shape, latent_dim):
inputs = Input(shape=input_shape)
x = inputs
x = Conv2D(32, 3, strides=2, padding='same')(x)
x = LeakyReLU()(x)
x = Conv2D(64, 3, strides=2, padding='same')(x)
x = LeakyReLU()(x)
x = Flatten()(x)
x = Dense(128, activation='relu')(x)
# Instead of outputting z directly, we output the mean and log_variance for the latent distribution
z_mean = Dense(latent_dim, name='z_mean')(x)
z_log_var = Dense(latent_dim, name='z_log_var')(x)
# Sampling function (defined later)
z = Sampling()([z_mean, z_log_var])
return Model(inputs, [z_mean, z_log_var, z], name='encoder')
Sampling Layer
We need a custom layer to sample z from the latent distribution defined by z_mean and z_log_var:
class Sampling(Layer):
"""Uses (z_mean, z_log_var) to sample z, the latent vector."""
def call(self, inputs):
z_mean, z_log_var = inputs
batch = tf.shape(z_mean)[0]
dim = tf.shape(z_mean)[1]
# Reparameterization trick
epsilon = tf.keras.backend.random_normal(shape=(batch, dim))
return z_mean + tf.exp(0.5 * z_log_var) * epsilon
Decoder
The decoder will use transposed convolutions to reconstruct the images from the latent space back to the original image dimensions:
# Decoder
def build_decoder(latent_dim, original_shape):
latent_inputs = Input(shape=(latent_dim,))
x = Dense(7 * 7 * 64, activation='relu')(latent_inputs)
x = Reshape((7, 7, 64))(x)
x = Conv2DTranspose(64, 3, strides=2, padding='same')(x)
x = LeakyReLU()(x)
x = Conv2DTranspose(32, 3, strides=2, padding='same')(x)
x = LeakyReLU()(x)
x = Conv2DTranspose(1, 3, activation='sigmoid', padding='same')(x)
return Model(latent_inputs, x, name='decoder')
VAE Model
Now, we'll define the VAE model by combining the encoder and decoder, and implement the custom loss function that includes the reconstruction loss and the KL divergence loss.
class VAE(Model):
def __init__(self, encoder, decoder, **kwargs):
super(VAE, self).__init__(**kwargs)
self.encoder = encoder
self.decoder = decoder
def call(self, inputs):
z_mean, z_log_var, z = self.encoder(inputs)
reconstructed = self.decoder(z)
return reconstructed
def train_step(self, data):
if isinstance(data, tuple):
data = data[0]
with tf.GradientTape() as tape:
z_mean, z_log_var, z = self.encoder(data)
reconstruction = self.decoder(z)
# Compute reconstruction loss
reconstruction_loss = tf.reduce_mean(
tf.reduce_sum(
keras.losses.binary_crossentropy(data, reconstruction), axis=(1, 2)
)
)
# Compute KL divergence
kl_loss = -0.5 * (1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var))
kl_loss = tf.reduce_mean(tf.reduce_sum(kl_loss, axis=1))
# Total loss
total_loss = reconstruction_loss + kl_loss
# Compute gradients and update weights
grads = tape.gradient(total_loss, self.trainable_weights)
self.optimizer.apply_gradients(zip(grads, self.trainable_weights))
# Update metrics
self.compiled_metrics.update_state(data, reconstruction)
# Return a dict mapping metric names to current value
return {
"loss": total_loss,
"reconstruction_loss": reconstruction_loss,
"kl_loss": kl_loss,
}
3. Compiling and Training the VAE
We'll compile the VAE with an optimizer and fit it on the Fashion MNIST dataset.
# Input shape
input_shape = (28, 28, 1)
# Build encoder and decoder
encoder = build_encoder(input_shape, latent_dim)
decoder = build_decoder(latent_dim, input_shape)
# Instantiate VAE
vae = VAE(encoder, decoder)
# Compile VAE
vae.compile(optimizer=keras.optimizers.Adam())
# Train VAE
history = vae.fit(
x_train,
epochs=20,
batch_size=128,
validation_data=(x_test, None)
)
4. Latent Space Interpolation
To visualize how the VAE transitions between different images in the latent space, we'll interpolate between two random points in the latent space and generate images.
def plot_latent_space_interpolation(vae, n=10):
# Randomly select two images from test set
idx1, idx2 = np.random.choice(len(x_test), size=2, replace=False)
img1, img2 = x_test[idx1:idx1+1], x_test[idx2:idx2+1]
# Encode images to get their latent representations
z_mean1, _, _ = vae.encoder.predict(img1)
z_mean2, _, _ = vae.encoder.predict(img2)
# Interpolate in latent space
z_interp = np.linspace(z_mean1, z_mean2, n)
# Decode interpolated latent vectors
interpolated_images = vae.decoder.predict(z_interp)
# Plot the images
plt.figure(figsize=(20, 4))
for i, img in enumerate(interpolated_images):
ax = plt.subplot(1, n, i + 1)
plt.imshow(img.squeeze(), cmap='gray')
ax.axis('off')
plt.show()
# Plot latent space interpolation
plot_latent_space_interpolation(vae, n=10)
5. Visualizing the Latent Space
We can visualize the latent space by encoding the test images and reducing the dimensionality of the latent means using t-SNE.
from sklearn.manifold import TSNE
# Encode the test images
z_mean, _, _ = vae.encoder.predict(x_test)
# Use t-SNE to reduce latent dimensions to 2D for visualization
tsne = TSNE(n_components=2)
z_tsne = tsne.fit_transform(z_mean)
# Plot the 2D latent space
plt.figure(figsize=(12, 10))
plt.scatter(z_tsne[:, 0], z_tsne[:, 1], c='blue', alpha=0.5)
plt.title('t-SNE projection of the latent space')
plt.xlabel('Dimension 1')
plt.ylabel('Dimension 2')
plt.show()
6. Experimenting with the Loss Function
You can experiment with the weight of the KL divergence term in the loss function to see its effect on the model's performance.
Modifying the VAE train_step
Add a weight to the KL divergence term:
class VAE(Model):
def __init__(self, encoder, decoder, kl_weight=1.0, **kwargs):
super(VAE, self).__init__(**kwargs)
self.encoder = encoder
self.decoder = decoder
self.kl_weight = kl_weight # Add KL weight parameter
def train_step(self, data):
if isinstance(data, tuple):
data = data[0]
with tf.GradientTape() as tape:
z_mean, z_log_var, z = self.encoder(data)
reconstruction = self.decoder(z)
reconstruction_loss = tf.reduce_mean(
tf.reduce_sum(
keras.losses.binary_crossentropy(data, reconstruction), axis=(1, 2)
)
)
kl_loss = -0.5 * (1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var))
kl_loss = tf.reduce_mean(tf.reduce_sum(kl_loss, axis=1))
# Apply KL weight
total_loss = reconstruction_loss + self.kl_weight * kl_loss
grads = tape.gradient(total_loss, self.trainable_weights)
self.optimizer.apply_gradients(zip(grads, self.trainable_weights))
self.compiled_metrics.update_state(data, reconstruction)
return {
"loss": total_loss,
"reconstruction_loss": reconstruction_loss,
"kl_loss": kl_loss,
}
You can now instantiate the VAE with different kl_weight values:
# Instantiate VAE with modified KL weight
vae = VAE(encoder, decoder, kl_weight=0.5)
# Compile and train as before
vae.compile(optimizer=keras.optimizers.Adam())
history = vae.fit(
x_train,
epochs=20,
batch_size=128,
validation_data=(x_test, None)
)
7. Experimenting with Latent Dimension Size
Try varying the size of the latent dimension latent_dim and observe the effects on the reconstruction quality and the latent space structure.
# For example, set latent_dim to 2 for visualization purposes
latent_dim = 2
# Rebuild encoder and decoder with new latent_dim
encoder = build_encoder(input_shape, latent_dim)
decoder = build_decoder(latent_dim, input_shape)
# Instantiate and compile VAE
vae = VAE(encoder, decoder)
vae.compile(optimizer=keras.optimizers.Adam())
# Train VAE
vae.fit(
x_train,
epochs=20,
batch_size=128,
validation_data=(x_test, None)
)
Now, since the latent space is 2-dimensional, you can directly visualize it:
# Encode test images to get 2D latent representations
z_mean, _, _ = vae.encoder.predict(x_test)
# Plot the latent space with labels
plt.figure(figsize=(12, 10))
plt.scatter(z_mean[:, 0], z_mean[:, 1], c='blue', alpha=0.5)
plt.title('2D Latent Space')
plt.xlabel('Dimension 1')
plt.ylabel('Dimension 2')
plt.show()
8. Additional Experiments
- Increasing Model Depth: Add more convolutional layers in the encoder and decoder to make the model deeper.
# Modify the encoder
def build_encoder(input_shape, latent_dim):
inputs = Input(shape=input_shape)
x = inputs
x = Conv2D(32, 3, strides=1, padding='same')(x)
x = LeakyReLU()(x)
x = Conv2D(64, 3, strides=2, padding='same')(x)
x = LeakyReLU()(x)
x = Conv2D(128, 3, strides=2, padding='same')(x)
x = LeakyReLU()(x)
x = Flatten()(x)
x = Dense(256, activation='relu')(x)
z_mean = Dense(latent_dim, name='z_mean')(x)
z_log_var = Dense(latent_dim, name='z_log_var')(x)
z = Sampling()([z_mean, z_log_var])
return Model(inputs, [z_mean, z_log_var, z], name='encoder')
# Similarly modify the decoder to match the architecture
9. Applying VAE to CIFAR-10
For an even more challenging task, you can try training the VAE on the CIFAR-10 dataset, which consists of small 32x32 color images across 10 classes.
Loading and Preprocessing CIFAR-10
from tensorflow.keras.datasets import cifar10
# Load CIFAR-10 dataset
(x_train, _), (x_test, _) = cifar10.load_data()
# Normalize images
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
# No need to expand dims as CIFAR-10 images are already shape (32, 32, 3)
input_shape = (32, 32, 3)
Adjusting the Model
Update the model architectures to accommodate the input shape and complexity of CIFAR-10 images.
- Increase the number of filters in convolutional layers.
- Modify the kernel sizes and strides.
- Adjust the layers in the decoder to output images of shape
(32, 32, 3).
Conclusion
By following these steps, you've:
- Extended your VAE to handle more complex data by switching to the Fashion MNIST dataset.
- Improved the model's architecture by introducing convolutional layers, making it better suited for image data.
- Experimented with the loss function to understand how the KL divergence weight affects the model's performance.
- Explored the latent space through interpolation and visualization, gaining insights into how the model represents data internally.
- Adjusted model parameters like latent dimension size, enhancing your understanding of their impact on the VAE's capability.
Further Exploration
-
CelebA Dataset: If you're interested in working with the CelebA (celebrity faces) dataset, note that it requires more computational resources due to its size and image resolutions. You'll need to adjust the model to handle color images of higher resolution.
-
Conditional VAEs: Explore Conditional VAEs (CVAEs), where you condition the generation process on additional information, like class labels, to control the attributes of generated images.
-
GANs and Beyond: Compare VAEs with Generative Adversarial Networks (GANs) in terms of generated image quality and training dynamics.
By iteratively experimenting and analyzing the outcomes, you'll gain a deeper understanding of variational autoencoders and their applications to complex datasets.