To enhance your Variational Autoencoder (VAE) training for learning more complex patterns across different datasets with varying image shapes, consider implementing the following strategies. These improvements focus on increasing model capacity, optimizing training procedures, and leveraging advanced architectural techniques tailored to each dataset's characteristics.
1. Increase Model Capacity
a. Deeper and Wider Networks
A more complex dataset like CIFAR-10 or CelebA benefits from deeper and wider networks to capture intricate patterns.
Encoder Enhancements:
def build_conv_encoder(input_shape, latent_dim):
input_img = Input(shape=input_shape)
x = Conv2D(64, kernel_size=3, strides=2, activation='relu', padding='same')(input_img)
x = Conv2D(128, kernel_size=3, strides=2, activation='relu', padding='same')(x)
x = Conv2D(256, kernel_size=3, strides=2, activation='relu', padding='same')(x)
x_shape = tf.keras.backend.int_shape(x)[1:]
x = Flatten()(x)
x = Dense(512, 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])
encoder = Model(input_img, [z_mean, z_log_var, z], name='encoder')
return encoder, x_shape
Decoder Enhancements:
def build_conv_decoder(x_shape, latent_dim, output_shape):
latent_inputs = Input(shape=(latent_dim,))
x = Dense(np.prod(x_shape), activation='relu')(latent_inputs)
x = Reshape(x_shape)(x)
x = Conv2DTranspose(256, kernel_size=3, strides=2, activation='relu', padding='same')(x)
x = Conv2DTranspose(128, kernel_size=3, strides=2, activation='relu', padding='same')(x)
x = Conv2DTranspose(64, kernel_size=3, strides=2, activation='relu', padding='same')(x)
# Handle different output sizes
if x.shape[1] != output_shape[0]:
x = Conv2DTranspose(32, kernel_size=3, strides=1, activation='relu', padding='same')(x)
outputs = Conv2DTranspose(
output_shape[2],
kernel_size=3,
activation='sigmoid',
padding='same'
)(x)
decoder = Model(latent_inputs, outputs, name='decoder')
return decoder
b. Adjust Latent Dimensions
Different datasets require varying latent dimensions to capture their complexity:
- MNIST/Fashion MNIST: Latent_dim = 16
- CIFAR-10: Latent_dim = 64
- CelebA: Latent_dim = 128
Adjusting the latent dimension allows the model to learn more nuanced representations where necessary.
2. Advanced Architectural Techniques
a. Batch Normalization
Incorporating Batch Normalization layers can stabilize and accelerate training.
Example:
from tensorflow.keras.layers import BatchNormalization
def build_conv_encoder(input_shape, latent_dim):
input_img = Input(shape=input_shape)
x = Conv2D(64, kernel_size=3, strides=2, padding='same')(input_img)
x = BatchNormalization()(x)
x = tf.keras.activations.relu(x)
x = Conv2D(128, kernel_size=3, strides=2, padding='same')(x)
x = BatchNormalization()(x)
x = tf.keras.activations.relu(x)
# Continue as before...
# ...
b. Residual Connections
Residual (skip) connections help in training deeper networks by mitigating vanishing gradient issues.
Example:
from tensorflow.keras.layers import Add
def residual_block(x, filters, kernel_size=3, strides=1):
shortcut = x
x = Conv2D(filters, kernel_size, strides=strides, padding='same', activation='relu')(x)
x = BatchNormalization()(x)
x = Conv2D(filters, kernel_size, strides=strides, padding='same')(x)
x = BatchNormalization()(x)
x = Add()([shortcut, x])
x = tf.keras.activations.relu(x)
return x
def build_conv_encoder(input_shape, latent_dim):
input_img = Input(shape=input_shape)
x = Conv2D(64, kernel_size=3, strides=2, padding='same')(input_img)
x = BatchNormalization()(x)
x = tf.keras.activations.relu(x)
x = residual_block(x, 64)
x = Conv2D(128, kernel_size=3, strides=2, padding='same')(x)
x = BatchNormalization()(x)
x = tf.keras.activations.relu(x)
x = residual_block(x, 128)
# Continue as before...
# ...
3. Optimize Training Procedures
a. Learning Rate Scheduling
Adjusting the learning rate during training can lead to better convergence.
Implementation:
from tensorflow.keras.callbacks import LearningRateScheduler
def scheduler(epoch, lr):
if epoch < 10:
return lr
elif epoch < 20:
return lr * 0.5
else:
return lr * 0.1
lr_callback = LearningRateScheduler(scheduler)
Usage in fit:
history = vae.fit(
x_train,
epochs=epochs,
batch_size=batch_size,
validation_data=(x_val, None),
callbacks=[lr_callback]
)
b. Early Stopping
Prevent overfitting by stopping training when the validation loss stops improving.
Implementation:
from tensorflow.keras.callbacks import EarlyStopping
early_stop = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
Usage in fit:
history = vae.fit(
x_train,
epochs=epochs,
batch_size=batch_size,
validation_data=(x_val, None),
callbacks=[lr_callback, early_stop]
)
c. KL Annealing (Beta-VAE)
Gradually increase the weight of the KL divergence term to allow the model to first learn to reconstruct before enforcing latent space regularization.
Modification in VAE Class:
class VAE(Model):
def __init__(self, encoder, decoder, kl_weight=1.0, kl_annealing_epochs=10, **kwargs):
super(VAE, self).__init__(**kwargs)
self.encoder = encoder
self.decoder = decoder
self.initial_kl_weight = kl_weight
self.kl_weight = kl_weight
self.kl_annealing_epochs = kl_annealing_epochs
self.current_epoch = 0
self.reconstruction_loss_tracker = tf.keras.metrics.Mean(name="reconstruction_loss")
self.kl_loss_tracker = tf.keras.metrics.Mean(name="kl_loss")
def train_step(self, data):
# Update KL weight
if self.current_epoch < self.kl_annealing_epochs:
self.kl_weight = self.initial_kl_weight * (self.current_epoch / self.kl_annealing_epochs)
else:
self.kl_weight = self.initial_kl_weight
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(
tf.keras.losses.binary_crossentropy(data, reconstruction),
axis=(1, 2)
)
)
kl_loss = -0.5 * tf.reduce_mean(
tf.reduce_sum(
z_log_var - tf.square(z_mean) - tf.exp(z_log_var) + 1,
axis=1
)
)
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))
# Update metrics
self.reconstruction_loss_tracker.update_state(reconstruction_loss)
self.kl_loss_tracker.update_state(kl_loss)
self.current_epoch += 1
return {"loss": total_loss,
"reconstruction_loss": self.reconstruction_loss_tracker.result(),
"kl_loss": self.kl_loss_tracker.result()}
4. Data Augmentation
Augmenting your data can help the model generalize better, especially on complex datasets like CelebA.
Implementation:
from tensorflow.keras.preprocessing.image import ImageDataGenerator
def get_data_generator(x_train, batch_size):
datagen = ImageDataGenerator(
rotation_range=15,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=True
)
datagen.fit(x_train)
return datagen.flow(x_train, batch_size=batch_size)
# Modify the training function to accept a generator
def train_vae(input_shape, latent_dim, x_train, x_val, epochs=30, batch_size=128, dataset_name='Dataset', augmentation=False):
# Build Encoder and Decoder
encoder, x_shape = build_conv_encoder(input_shape, latent_dim)
decoder = build_conv_decoder(x_shape, latent_dim, input_shape)
vae = VAE(encoder, decoder, kl_weight=0.1)
vae.compile(optimizer='adam')
if augmentation:
datagen = get_data_generator(x_train, batch_size)
steps_per_epoch = len(x_train) // batch_size
history = vae.fit(
datagen,
steps_per_epoch=steps_per_epoch,
epochs=epochs,
validation_data=(x_val, None),
callbacks=[lr_callback, early_stop]
)
else:
history = vae.fit(
x_train,
epochs=epochs,
batch_size=batch_size,
validation_data=(x_val, None),
callbacks=[lr_callback, early_stop]
)
# Continue with visualization...
# ...
Usage for CelebA:
vae_celeba = train_vae(
input_shape=(64, 64, 3),
latent_dim=128,
x_train=x_train_celeba,
x_val=x_val_celeba,
epochs=50,
batch_size=128,
dataset_name='CelebA',
augmentation=True
)
5. Use of Advanced Loss Functions
Incorporate additional loss components to encourage the learning of more meaningful features.
a. Perceptual Loss
Calculates loss based on high-level features from a pre-trained network (e.g., VGG). This encourages the model to preserve semantic information.
Implementation Overview:
- Load a pre-trained network without the top layers.
- Extract features from intermediate layers.
- Compute the loss between original and reconstructed images in the feature space.
Note: Implementing perceptual loss can be computationally intensive and requires careful tuning.
6. Hyperparameter Tuning
Systematically explore different hyperparameters to find the optimal configuration for each dataset.
- Latent Dimensions: Experiment with various sizes.
- Learning Rates: Try different initial learning rates.
- Batch Sizes: Larger batches may stabilize training but require more memory.
- Activation Functions: Explore alternatives like LeakyReLU or ELU.
Example:
# Try different latent dimensions
latent_dimensions = [32, 64, 128]
for latent_dim in latent_dimensions:
vae = train_vae(
input_shape=(64, 64, 3),
latent_dim=latent_dim,
x_train=x_train_celeba,
x_val=x_val_celeba,
epochs=30,
batch_size=128,
dataset_name=f'CelebA Latent_{latent_dim}',
augmentation=True
)
7. Implementing a More Sophisticated VAE Variant
Consider using more advanced VAE variants that better capture complex data distributions.
a. β-VAE
Introduces a hyperparameter β to balance reconstruction and KL divergence, promoting disentangled representations.
# Initialize VAE with increased KL weight
vae = VAE(encoder, decoder, kl_weight=4.0) # β = 4.0 for stronger regularization
b. Conditional VAE (cVAE)
Incorporates additional information (e.g., class labels) to guide the generation process.
Note: Requires modifying the encoder and decoder to accept conditional inputs.
8. Visualization and Monitoring
Regularly visualize latent spaces and reconstructions to monitor the learning process.
a. Latent Space Visualization
Use techniques like t-SNE or PCA to visualize how the latent representations cluster.
Example:
from sklearn.manifold import TSNE
def plot_latent_space(encoder, x, y=None):
z_mean, _, _ = encoder.predict(x)
tsne = TSNE(n_components=2)
z_tsne = tsne.fit_transform(z_mean)
plt.figure(figsize=(10, 8))
if y is not None:
plt.scatter(z_tsne[:,0], z_tsne[:,1], c=y, cmap='viridis')
else:
plt.scatter(z_tsne[:,0], z_tsne[:,1])
plt.xlabel('Dimension 1')
plt.ylabel('Dimension 2')
plt.title('Latent Space Visualization')
plt.show()
# Usage after training
plot_latent_space(vae.encoder, x_val_celeba, y=labels) # Assuming labels are available
b. Reconstruction and Generation Monitoring
Regularly evaluate and visualize reconstructions and generated samples to ensure quality improvements.
Example:
def generate_and_plot_samples(decoder, latent_dim, num_samples=10):
random_latent_vectors = np.random.normal(size=(num_samples, latent_dim))
generated_images = decoder.predict(random_latent_vectors)
plot_reconstructions(generated_images, generated_images, input_shape=(64, 64, 3), num_images=num_samples)
# Usage after training
generate_and_plot_samples(vae.decoder, latent_dim=128)
9. Handling Different Image Shapes
Ensure that your encoder and decoder architectures are appropriately adjusted for different image shapes. Here's how you can generalize the architecture building functions:
def build_conv_encoder_general(input_shape, latent_dim, base_filters=32, depth=4):
input_img = Input(shape=input_shape)
x = input_img
filters = base_filters
for _ in range(depth):
x = Conv2D(filters, kernel_size=3, strides=2, padding='same')(x)
x = BatchNormalization()(x)
x = tf.keras.activations.relu(x)
filters *= 2
x_shape = tf.keras.backend.int_shape(x)[1:]
x = Flatten()(x)
x = Dense(filters, 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])
encoder = Model(input_img, [z_mean, z_log_var, z], name='encoder')
return encoder, x_shape
def build_conv_decoder_general(x_shape, latent_dim, output_shape, base_filters=16, depth=4):
latent_inputs = Input(shape=(latent_dim,))
x = Dense(np.prod(x_shape), activation='relu')(latent_inputs)
x = Reshape(x_shape)(x)
filters = x_shape[-1]
for _ in range(depth):
x = Conv2DTranspose(filters, kernel_size=3, strides=2, padding='same', activation='relu')(x)
filters = max(filters // 2, base_filters)
outputs = Conv2DTranspose(
output_shape[2],
kernel_size=3,
activation='sigmoid',
padding='same'
)(x)
decoder = Model(latent_inputs, outputs, name='decoder')
return decoder
Usage:
def train_vae_general(input_shape, latent_dim, x_train, x_val, epochs=30, batch_size=128, dataset_name='Dataset', base_filters=32, depth=4):
encoder, x_shape = build_conv_encoder_general(input_shape, latent_dim, base_filters, depth)
decoder = build_conv_decoder_general(x_shape, latent_dim, input_shape, base_filters, depth)
vae = VAE(encoder, decoder, kl_weight=0.1)
vae.compile(optimizer='adam')
# Continue with training as before...
# ...
This general approach allows you to adjust the base_filters and depth parameters based on the complexity and size of each dataset.
10. Regularization Techniques
Implement dropout or L2 regularization to prevent overfitting, especially on complex datasets.
Example with Dropout:
from tensorflow.keras.layers import Dropout
def build_conv_encoder_with_dropout(input_shape, latent_dim):
input_img = Input(shape=input_shape)
x = Conv2D(64, kernel_size=3, strides=2, padding='same', activation='relu')(input_img)
x = Dropout(0.3)(x)
x = Conv2D(128, kernel_size=3, strides=2, padding='same', activation='relu')(x)
x = Dropout(0.3)(x)
# Continue as before...
# ...
Example with L2 Regularization:
from tensorflow.keras.regularizers import l2
def build_conv_encoder_with_l2(input_shape, latent_dim, l2_factor=1e-4):
input_img = Input(shape=input_shape)
x = Conv2D(64, kernel_size=3, strides=2, padding='same', activation='relu',
kernel_regularizer=l2(l2_factor))(input_img)
x = Conv2D(128, kernel_size=3, strides=2, padding='same', activation='relu',
kernel_regularizer=l2(l2_factor))(x)
# Continue as before...
# ...
11. Summary of Recommendations
-
Enhance Model Capacity:
- Deeper and wider convolutional layers.
- Adjust latent dimensions based on dataset complexity.
-
Implement Advanced Architectures:
- Use Batch Normalization and Residual Connections.
- Explore advanced VAE variants like β-VAE.
-
Optimize Training Procedures:
- Apply learning rate scheduling and early stopping.
- Utilize KL annealing for balanced latent space regularization.
-
Data Augmentation:
- Employ techniques like rotation, shifting, and flipping to increase data variability.
-
Regularization:
- Incorporate Dropout or L2 regularization to prevent overfitting.
-
Hyperparameter Tuning:
- Systematically experiment with different hyperparameters for optimal performance.
-
Visualization and Monitoring:
- Regularly visualize latent spaces and generated samples to assess learning progress.
-
Tailor Architectures to Image Shapes:
- Use generalized encoder and decoder builders to accommodate different input shapes.
By systematically applying these improvements, your VAE should be better equipped to learn and represent more complex patterns across diverse datasets. Remember to iterate and validate each change to understand its impact on model performance.
Complete Example: Enhanced VAE Training Function
Below is a comprehensive example incorporating several of the recommended improvements:
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Reshape, Conv2DTranspose, Conv2D, Flatten, BatchNormalization, Dropout
from tensorflow.keras.models import Model
from tensorflow.keras.datasets import fashion_mnist, mnist, cifar10
import numpy as np
from tensorflow.keras.layers import Layer, Add
from tensorflow.keras.callbacks import LearningRateScheduler, EarlyStopping
from sklearn.model_selection import train_test_split
from tensorflow.keras.preprocessing.image import load_img, img_to_array
import matplotlib.pyplot as plt
# Sampling Layer
class Sampling(Layer):
def call(self, inputs):
z_mean, z_log_var = inputs
epsilon = tf.keras.backend.random_normal(shape=tf.shape(z_mean))
return z_mean + tf.exp(0.5 * z_log_var) * epsilon
# Convolutional Encoder with Residual Blocks
def residual_block(x, filters, kernel_size=3, strides=1):
shortcut = x
x = Conv2D(filters, kernel_size, strides=strides, padding='same')(x)
x = BatchNormalization()(x)
x = tf.keras.activations.relu(x)
x = Conv2D(filters, kernel_size, strides=strides, padding='same')(x)
x = BatchNormalization()(x)
x = Add()([shortcut, x])
x = tf.keras.activations.relu(x)
return x
def build_conv_encoder(input_shape, latent_dim):
input_img = Input(shape=input_shape)
x = Conv2D(64, kernel_size=3, strides=2, padding='same')(input_img)
x = BatchNormalization()(x)
x = tf.keras.activations.relu(x)
x = residual_block(x, 64)
x = Conv2D(128, kernel_size=3, strides=2, padding='same')(x)
x = BatchNormalization()(x)
x = tf.keras.activations.relu(x)
x = residual_block(x, 128)
x = Conv2D(256, kernel_size=3, strides=2, padding='same')(x)
x = BatchNormalization()(x)
x = tf.keras.activations.relu(x)
x = residual_block(x, 256)
x_shape = tf.keras.backend.int_shape(x)[1:]
x = Flatten()(x)
x = Dense(512, 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])
encoder = Model(input_img, [z_mean, z_log_var, z], name='encoder')
return encoder, x_shape
# Convolutional Decoder with Transposed Convolutions
def build_conv_decoder(x_shape, latent_dim, output_shape):
latent_inputs = Input(shape=(latent_dim,))
x = Dense(np.prod(x_shape), activation='relu')(latent_inputs)
x = Reshape(x_shape)(x)
x = Conv2DTranspose(256, kernel_size=3, strides=2, padding='same', activation='relu')(x)
x = BatchNormalization()(x)
x = Conv2DTranspose(128, kernel_size=3, strides=2, padding='same', activation='relu')(x)
x = BatchNormalization()(x)
x = Conv2DTranspose(64, kernel_size=3, strides=2, padding='same', activation='relu')(x)
x = BatchNormalization()(x)
outputs = Conv2DTranspose(
output_shape[2],
kernel_size=3,
activation='sigmoid',
padding='same'
)(x)
decoder = Model(latent_inputs, outputs, name='decoder')
return decoder
# VAE Model with KL Annealing
class VAE(Model):
def __init__(self, encoder, decoder, kl_weight=1.0, kl_annealing_epochs=10, **kwargs):
super(VAE, self).__init__(**kwargs)
self.encoder = encoder
self.decoder = decoder
self.initial_kl_weight = kl_weight
self.kl_weight = kl_weight
self.kl_annealing_epochs = kl_annealing_epochs
self.current_epoch = 0
self.reconstruction_loss_tracker = tf.keras.metrics.Mean(name="reconstruction_loss")
self.kl_loss_tracker = tf.keras.metrics.Mean(name="kl_loss")
def call(self, inputs):
z_mean, z_log_var, z = self.encoder(inputs)
reconstruction = self.decoder(z)
return reconstruction
def train_step(self, data):
# Update KL weight
if self.current_epoch < self.kl_annealing_epochs:
self.kl_weight = self.initial_kl_weight * (self.current_epoch / self.kl_annealing_epochs)
else:
self.kl_weight = self.initial_kl_weight
with tf.GradientTape() as tape:
z_mean, z_log_var, z = self.encoder(data)
reconstruction = self.decoder(z)
if data.shape[-1] == 1:
# For grayscale images
reconstruction_loss = tf.reduce_mean(
tf.reduce_sum(
tf.keras.losses.binary_crossentropy(data, reconstruction),
axis=(1, 2)
)
)
else:
# For color images
reconstruction_loss = tf.reduce_mean(
tf.reduce_sum(
tf.keras.losses.mean_squared_error(data, reconstruction),
axis=(1, 2, 3)
)
)
kl_loss = -0.5 * tf.reduce_mean(
tf.reduce_sum(
z_log_var - tf.square(z_mean) - tf.exp(z_log_var) + 1,
axis=1
)
)
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))
# Update metrics
self.reconstruction_loss_tracker.update_state(reconstruction_loss)
self.kl_loss_tracker.update_state(kl_loss)
self.current_epoch += 1
return {"loss": total_loss,
"reconstruction_loss": self.reconstruction_loss_tracker.result(),
"kl_loss": self.kl_loss_tracker.result()}
def test_step(self, data):
z_mean, z_log_var, z = self.encoder(data)
reconstruction = self.decoder(z)
if data.shape[-1] == 1:
reconstruction_loss = tf.reduce_mean(
tf.reduce_sum(
tf.keras.losses.binary_crossentropy(data, reconstruction),
axis=(1, 2)
)
)
else:
reconstruction_loss = tf.reduce_mean(
tf.reduce_sum(
tf.keras.losses.mean_squared_error(data, reconstruction),
axis=(1, 2, 3)
)
)
kl_loss = -0.5 * tf.reduce_mean(
tf.reduce_sum(
z_log_var - tf.square(z_mean) - tf.exp(z_log_var) + 1,
axis=1
)
)
total_loss = reconstruction_loss + self.kl_weight * kl_loss
# Update metrics
self.reconstruction_loss_tracker.update_state(reconstruction_loss)
self.kl_loss_tracker.update_state(kl_loss)
return {"loss": total_loss,
"reconstruction_loss": self.reconstruction_loss_tracker.result(),
"kl_loss": self.kl_loss_tracker.result()}
@property
def metrics(self):
return [self.reconstruction_loss_tracker, self.kl_loss_tracker]
# Training Function with Enhancements
def train_vae(input_shape, latent_dim, x_train, x_val, epochs=30, batch_size=128, dataset_name='Dataset', kl_annealing_epochs=10):
# Build Encoder and Decoder
encoder, x_shape = build_conv_encoder(input_shape, latent_dim)
decoder = build_conv_decoder(x_shape, latent_dim, input_shape)
# Initialize VAE
vae = VAE(encoder, decoder, kl_weight=1.0, kl_annealing_epochs=kl_annealing_epochs)
vae.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3))
# Define Callbacks
def scheduler(epoch, lr):
if epoch < 10:
return lr
elif epoch < 20:
return lr * 0.5
else:
return lr * 0.1
lr_callback = LearningRateScheduler(scheduler)
early_stop = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
# Train VAE
history = vae.fit(
x_train,
epochs=epochs,
batch_size=batch_size,
validation_data=(x_val, None),
callbacks=[lr_callback, early_stop]
)
# Visualization of Training Losses
plt.figure(figsize=(8,6))
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['reconstruction_loss'], label='Reconstruction Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.title(f'Training Losses for VAE on {dataset_name}')
plt.show()
# Reconstruct and Plot Images
x_reconstructed = vae.predict(x_val[:10])
# Function to plot reconstructions
def plot_reconstructions(x_original, x_reconstructed, input_shape, num_images=10):
plt.figure(figsize=(20, 4))
for i in range(num_images):
# Original
ax = plt.subplot(2, num_images, i + 1)
if input_shape[-1] == 1:
plt.imshow(x_original[i].squeeze(), cmap='gray')
else:
plt.imshow(x_original[i])
ax.axis('off')
# Reconstructed
ax = plt.subplot(2, num_images, i + 1 + num_images)
if x_reconstructed.shape[-1] == 1:
plt.imshow(x_reconstructed[i].squeeze(), cmap='gray')
else:
plt.imshow(x_reconstructed[i])
ax.axis('off')
plt.tight_layout()
plt.show()
plot_reconstructions(x_val[:10], x_reconstructed, input_shape)
return vae
# Example Usage: Training on CIFAR-10
# Load CIFAR-10 Data
(x_train_cifar, _), (x_test_cifar, _) = cifar10.load_data()
x_train_cifar = x_train_cifar.astype('float32') / 255.
x_test_cifar = x_test_cifar.astype('float32') / 255.
print(f"x_train_cifar shape: {x_train_cifar.shape}") # (50000,32,32,3)
print(f"x_test_cifar shape: {x_test_cifar.shape}") # (10000,32,32,3)
# Train VAE on CIFAR-10
vae_cifar = train_vae(
input_shape=(32, 32, 3),
latent_dim=64,
x_train=x_train_cifar,
x_val=x_test_cifar,
epochs=50,
batch_size=256,
dataset_name='CIFAR-10',
kl_annealing_epochs=20
)
Implementing these enhancements should significantly improve your VAE's ability to learn and represent complex patterns across different datasets. Ensure to monitor training progress and validate changes iteratively to achieve optimal performance.