if name == "main":
# Load Data
dataset = "fashion_mnist" # Change to "cifar10" for CIFAR-10
if dataset == "fashion_mnist":
x_train, x_test = load_fashion_mnist()
input_shape = x_train.shape[1:]
elif dataset == "cifar10":
x_train, x_test = load_cifar10()
input_shape = x_train.shape[1:]
elif dataset == "celebA":
local_extract_path = '/content/images/image'
image_paths = glob.glob(os.path.join(local_extract_path, '*.jpg'))
images = [np.array(Image.open(img_path).resize((64, 64))) for img_path in image_paths]
x_train = np.array(images)
x_test = np.array(images)
input_shape = x_train.shape[1:]
else:
raise ValueError("Unsupported dataset")
Fashion MNIST: Lepsze wyzwanie, bo zawiera obrazy ubrań, które są bardziej skomplikowane niż cyfry.
CIFAR-10 lub CIFAR-100: Bardziej zaawansowane obrazy w kolorze, co wprowadza dodatkową złożoność i wymaga użycia konwolucyjnych warstw.
CelebA: Zbiór zdjęć twarzy, przydatny do badania jakości generowania realistycznych obrazów ludzi. Ciekawą możliwością jest manipulacja cechami twarzy w przestrzeni latentnej, np. rozpoznawanie emocji.
(4pt) Zmiana architektury modelu:
code
Konwolucyjne VAE: Dodanie warstw konwolucyjnych do enkodera i dekodera może poprawić zdolność modelu do uchwycenia złożonych wzorców.
Głębsza sieć: Dodanie większej liczby warstw oraz testowanie różnych liczby jednostek w warstwach ukrytych.
Eksperymenty z rozmiarami przestrzeni latentnej $z$: Zmniejszenie lub zwiększenie wymiarów wektora latentnego i porównanie jakości generacji.
(4pt) Eksperymenty z funkcją straty:
code
Sprawdzenie, jak zmiana wagi komponentu Kullbacka-Leiblera wpływa na balans między rekonstrukcją a regularnością przestrzeni latentnej.
Dodanie dodatkowego termu w funkcji straty, który kładzie większy nacisk na rekonstrukcję detali.
(4pt) Interpolacje w przestrzeni latentnej:
code
Wygenerowanie próbek obrazów, które są interpolacją pomiędzy dwoma punktami w przestrzeni latentnej. Pozwala to na zaobserwowanie, jak VAE przechodzi między dwoma obrazami i czy generowane obrazy są realistyczne.
Assistant
(4pt) Wizualizacja przestrzeni latentnej:
code
Redukcja przestrzeni latentnej do 2D (PCA lub t-SNE), aby zobaczyć, jak VAE rozdziela różne klasy obiektów.
Tworzenie mapy przestrzeni latentnej dla CelebA lub Fashion MNIST, co pozwala na zbadanie klastrów i przejść między różnymi rodzajami ubrań lub cechami twarzy.
!Wykonaj to zadanie dla moich zbiorów danych!
Sure! I can help you implement the tasks you've outlined for your datasets. Below, I'll guide you through each task step-by-step, providing code snippets and explanations to modify your Variational Autoencoder (VAE) accordingly. We'll cover:
Changing the Model Architecture
Experimenting with the Loss Function
Performing Interpolations in the Latent Space
Visualizing the Latent Space
Assuming you're using TensorFlow with Keras for your VAE implementation, here's how you can proceed.
1. Changing the Model Architecture
a. Convolutional VAE
Using convolutional layers can help the VAE capture spatial hierarchies in image data more effectively. Here's how you can modify your encoder and decoder to use convolutional layers.
python
import tensorflow as tf
from tensorflow.keras import layers, models, backend as K
# Define latent dimension
latent_dim = 2 # You can experiment with different dimensions
# Encoder
def build_encoder(input_shape, latent_dim):
encoder_inputs = layers.Input(shape=input_shape)
x = layers.Conv2D(32, 3, activation='relu', strides=2, padding='same')(encoder_inputs)
x = layers.Conv2D(64, 3, activation='relu', strides=2, padding='same')(x)
x = layers.Flatten()(x)
x = layers.Dense(128, activation='relu')(x)
z_mean = layers.Dense(latent_dim, name='z_mean')(x)
z_log_var = layers.Dense(latent_dim, name='z_log_var')(x)
# Sampling layer
def sampling(args):
z_mean, z_log_var = args
epsilon = K.random_normal(shape=(K.shape(z_mean)[0], latent_dim),
mean=0., stddev=1.0)
return z_mean + K.exp(0.5 * z_log_var) * epsilon
z = layers.Lambda(sampling, output_shape=(latent_dim,), name='z')([z_mean, z_log_var])
encoder = models.Model(encoder_inputs, [z_mean, z_log_var, z], name='encoder')
encoder.summary()
return encoder
# Decoder
def build_decoder(output_shape, latent_dim):
decoder_inputs = layers.Input(shape=(latent_dim,))
x = layers.Dense(16 * 16 * 64, activation='relu')(decoder_inputs)
x = layers.Reshape((16, 16, 64))(x)
x = layers.Conv2DTranspose(64, 3, activation='relu', strides=2, padding='same')(x)
x = layers.Conv2DTranspose(32, 3, activation='relu', strides=2, padding='same')(x)
decoder_outputs = layers.Conv2DTranspose(output_shape[2], 3, activation='sigmoid', padding='same')(x)
decoder = models.Model(decoder_inputs, decoder_outputs, name='decoder')
decoder.summary()
return decoder
# Building encoder and decoder
input_shape = x_train.shape[1:] # Example: (64, 64, 3) for CelebA
encoder = build_encoder(input_shape, latent_dim)
decoder = build_decoder(input_shape, latent_dim)
# VAE Model
vae_inputs = encoder.input
z_mean, z_log_var, z = encoder(vae_inputs)
vae_outputs = decoder(z)
vae = models.Model(vae_inputs, vae_outputs, name='vae')
vae.summary()
b. Deeper Network
You can add more layers to both the encoder and decoder to make the network deeper.
python
# Example: Adding more Dense layers in the encoder
def build_deep_encoder(input_shape, latent_dim):
encoder_inputs = layers.Input(shape=input_shape)
x = layers.Conv2D(32, 3, activation='relu', strides=2, padding='same')(encoder_inputs)
x = layers.Conv2D(64, 3, activation='relu', strides=2, padding='same')(x)
x = layers.Conv2D(128, 3, activation='relu', strides=2, padding='same')(x)
x = layers.Flatten()(x)
x = layers.Dense(256, activation='relu')(x)
x = layers.Dense(128, activation='relu')(x)
z_mean = layers.Dense(latent_dim, name='z_mean')(x)
z_log_var = layers.Dense(latent_dim, name='z_log_var')(x)
z = layers.Lambda(sampling, output_shape=(latent_dim,), name='z')([z_mean, z_log_var])
encoder = models.Model(encoder_inputs, [z_mean, z_log_var, z], name='deep_encoder')
encoder.summary()
return encoder
# Similarly, you can add more layers to the decoder
def build_deep_decoder(output_shape, latent_dim):
decoder_inputs = layers.Input(shape=(latent_dim,))
x = layers.Dense(256, activation='relu')(decoder_inputs)
x = layers.Dense(16 * 16 * 128, activation='relu')(x)
x = layers.Reshape((16, 16, 128))(x)
x = layers.Conv2DTranspose(128, 3, activation='relu', strides=2, padding='same')(x)
x = layers.Conv2DTranspose(64, 3, activation='relu', strides=2, padding='same')(x)
x = layers.Conv2DTranspose(32, 3, activation='relu', strides=2, padding='same')(x)
decoder_outputs = layers.Conv2DTranspose(output_shape[2], 3, activation='sigmoid', padding='same')(x)
decoder = models.Model(decoder_inputs, decoder_outputs, name='deep_decoder')
decoder.summary()
return decoder
# Building deeper encoder and decoder
encoder = build_deep_encoder(input_shape, latent_dim)
decoder = build_deep_decoder(input_shape, latent_dim)
# Reconstruct VAE Model with deeper architecture
vae_outputs = decoder(z)
vae = models.Model(vae_inputs, vae_outputs, name='deep_vae')
vae.summary()
c. Experimenting with Latent Dimensions
You can experiment with different sizes of the latent space to see how it affects the quality of generated images.
Try varying latent_dim (e.g., 2, 10, 20) and observe the reconstruction quality and generative capabilities.
2. Experimenting with the Loss Function
a. Balancing Reconstruction and KL Divergence
Adjusting the weight of the KL divergence term can balance how much the model focuses on reconstruction versus keeping the latent space regularized.
python
# Define loss with weighted KL divergence
class VAE(tf.keras.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
def call(self, inputs):
z_mean, z_log_var, z = self.encoder(inputs)
reconstructed = self.decoder(z)
reconstruction_loss = tf.reduce_mean(
tf.keras.losses.binary_crossentropy(inputs, reconstructed)
)
reconstruction_loss *= input_shape[0] * input_shape[1] * input_shape[2]
kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)
kl_loss = tf.reduce_mean(-0.5 * tf.reduce_sum(kl_loss, axis=1))
total_loss = reconstruction_loss + self.kl_weight * kl_loss
self.add_loss(total_loss)
return reconstructed
# Instantiate and compile VAE with different kl_weight
kl_weight = 0.5 # You can experiment with values like 0.1, 1.0, 5.0
vae = VAE(encoder, decoder, kl_weight)
vae.compile(optimizer='adam')
Experiment with different kl_weight values to find the optimal balance for your dataset.
b. Adding a Detail-Preserving Term
To encourage the model to preserve more details during reconstruction, you can add an additional loss component, such as Mean Squared Error (MSE).
python
class VAEWithDetailLoss(tf.keras.Model):
def __init__(self, encoder, decoder, kl_weight=1.0, detail_weight=1.0, **kwargs):
super(VAEWithDetailLoss, self).__init__(**kwargs)
self.encoder = encoder
self.decoder = decoder
self.kl_weight = kl_weight
self.detail_weight = detail_weight
def call(self, inputs):
z_mean, z_log_var, z = self.encoder(inputs)
reconstructed = self.decoder(z)
# Binary crossentropy for reconstruction
reconstruction_loss = tf.reduce_mean(
tf.keras.losses.binary_crossentropy(inputs, reconstructed)
)
reconstruction_loss *= input_shape[0] * input_shape[1] * input_shape[2]
# MSE for detail preservation
detail_loss = tf.reduce_mean(tf.keras.losses.mean_squared_error(inputs, reconstructed))
# KL divergence
kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)
kl_loss = tf.reduce_mean(-0.5 * tf.reduce_sum(kl_loss, axis=1))
# Total loss
total_loss = reconstruction_loss + self.kl_weight * kl_loss + self.detail_weight * detail_loss
self.add_loss(total_loss)
return reconstructed
# Instantiate and compile VAE with detail loss
kl_weight = 1.0
detail_weight = 10.0 # Adjust based on how much emphasis you want on details
vae = VAEWithDetailLoss(encoder, decoder, kl_weight, detail_weight)
vae.compile(optimizer='adam')
Adjust detail_weight to control the importance of detail preservation.
3. Performing Interpolations in the Latent Space
Interpolating between two points in the latent space can help visualize how the VAE transitions between different generated images.
python
import numpy as np
import matplotlib.pyplot as plt
def interpolate_latent_space(encoder, decoder, data, num_steps=10):
# Select two random samples from the data
idx = np.random.choice(len(data), 2, replace=False)
sample1 = data[idx[0]:idx[0]+1]
sample2 = data[idx[1]:idx[1]+1]
# Encode the samples to get the latent representations
z_mean1, z_log_var1, z1 = encoder.predict(sample1)
z_mean2, z_log_var2, z2 = encoder.predict(sample2)
# Linear interpolation
interpolated_z = np.linspace(z1, z2, num_steps)
# Decode the interpolated latent vectors
interpolated_images = decoder.predict(interpolated_z)
# Plot the interpolated images
plt.figure(figsize=(20, 4))
for i in range(num_steps):
ax = plt.subplot(1, num_steps, i + 1)
plt.imshow(interpolated_images[i])
plt.axis('off')
plt.show()
# Example usage with your training data
interpolate_latent_space(encoder, decoder, x_train, num_steps=10)
This function selects two random images from your dataset, encodes them into the latent space, interpolates between their latent vectors, decodes the intermediate points, and visualizes the transition.
4. Visualizing the Latent Space
Reducing the latent space to 2D using PCA or t-SNE allows you to visualize how different classes or features are organized.
a. Using PCA for Dimensionality Reduction
python
from sklearn.decomposition import PCA
def visualize_latent_space_pca(encoder, data, labels=None):
# Encode all data to get mean latent vectors
z_mean, z_log_var, z = encoder.predict(data, batch_size=128)
# If latent_dim > 2, reduce dimensions with PCA
if z.shape[1] > 2:
pca = PCA(n_components=2)
z_pca = pca.fit_transform(z)
else:
z_pca = z
plt.figure(figsize=(10, 8))
if labels is not None:
scatter = plt.scatter(z_pca[:, 0], z_pca[:, 1], c=labels, cmap='viridis', alpha=0.5)
plt.colorbar(scatter)
else:
plt.scatter(z_pca[:, 0], z_pca[:, 1], alpha=0.5)
plt.xlabel('PCA Component 1')
plt.ylabel('PCA Component 2')
plt.title('Latent Space Visualization with PCA')
plt.show()
# Example usage with Fashion MNIST labels
# Assuming y_train contains labels
visualize_latent_space_pca(encoder, x_train, labels=y_train)
b. Using t-SNE for Non-linear Dimensionality Reduction
python
from sklearn.manifold import TSNE
def visualize_latent_space_tsne(encoder, data, labels=None):
# Encode all data to get mean latent vectors
z_mean, z_log_var, z = encoder.predict(data, batch_size=128)
# t-SNE transformation
tsne = TSNE(n_components=2, verbose=1, random_state=42)
z_tsne = tsne.fit_transform(z)
plt.figure(figsize=(10, 8))
if labels is not None:
scatter = plt.scatter(z_tsne[:, 0], z_tsne[:, 1], c=labels, cmap='viridis', alpha=0.5)
plt.colorbar(scatter)
else:
plt.scatter(z_tsne[:, 0], z_tsne[:, 1], alpha=0.5)
plt.xlabel('t-SNE Component 1')
plt.ylabel('t-SNE Component 2')
plt.title('Latent Space Visualization with t-SNE')
plt.show()
# Example usage with Fashion MNIST labels
visualize_latent_space_tsne(encoder, x_train, labels=y_train)
These visualizations help you understand how well the VAE has organized different classes or features in the latent space.
5. Integrating Everything into the Training Loop
Here's how you can integrate the above modifications into your main training loop.
python
import os
import glob
import numpy as np
from PIL import Image
def load_fashion_mnist():
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()
# Normalize and reshape
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)
return (x_train, y_train), (x_test, y_test)
def load_cifar10():
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
# Normalize
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
return (x_train, y_train), (x_test, y_test)
if __name__ == "__main__":
# Load Data
dataset = "fashion_mnist" # Change to "cifar10" or "celebA" as needed
if dataset == "fashion_mnist":
(x_train, y_train), (x_test, y_test) = load_fashion_mnist()
input_shape = x_train.shape[1:]
elif dataset == "cifar10":
(x_train, y_train), (x_test, y_test) = load_cifar10()
input_shape = x_train.shape[1:]
elif dataset == "celebA":
local_extract_path = '/content/images/image'
image_paths = glob.glob(os.path.join(local_extract_path, '*.jpg'))
images = [np.array(Image.open(img_path).resize((64, 64))) for img_path in image_paths]
x_train = np.array(images).astype('float32') / 255.
x_test = x_train.copy() # For simplicity; in practice, split properly
input_shape = x_train.shape[1:]
else:
raise ValueError("Unsupported dataset")
# Define model parameters
latent_dim = 2 # You can experiment with different latent dimensions
kl_weight = 0.1 # Experiment with different KL weights
detail_weight = 1.0 # If using detail-preserving loss
# Build encoder and decoder
encoder = build_encoder(input_shape, latent_dim)
decoder = build_decoder(input_shape, latent_dim)
# Build VAE with custom loss
vae = VAE(encoder, decoder, kl_weight)
vae.compile(optimizer='adam')
# Train the VAE
vae.fit(x_train,
epochs=50,
batch_size=128,
validation_data=(x_test, None))
# After training, perform interpolations
interpolate_latent_space(encoder, decoder, x_test, num_steps=10)
# Visualize latent space
visualize_latent_space_pca(encoder, x_test, labels=y_test if dataset != "celebA" else None)
# For CelebA, you might need specific labels like attributes
Notes:
Data Normalization: Ensure all your datasets are normalized appropriately. For RGB images (like CIFAR-10 and CelebA), scaling pixel values to [0, 1] is common.
Labels for Visualization: For datasets like Fashion MNIST and CIFAR-10, labels are readily available. For CelebA, you might need to use attribute labels if you want to color the latent space based on specific attributes.
Training Parameters: Adjust epochs, batch_size, kl_weight, and latent_dim based on your computational resources and desired outcomes.
Model Saving: Consider saving your trained models for future use.
python
# Save the models
encoder.save('encoder_model.h5')
decoder.save('decoder_model.h5')
vae.save('vae_model.h5')
# To load later
# encoder = tf.keras.models.load_model('encoder_model.h5', compile=False)
# decoder = tf.keras.models.load_model('decoder_model.h5', compile=False)
Additional Tips
Monitoring Training: Use callbacks like ModelCheckpoint and EarlyStopping to monitor and save the best models.
Hyperparameter Tuning: Experiment with different architectures, latent dimensions, and loss weights to find the optimal configuration for your specific dataset.
Advanced Loss Functions: Consider using other reconstruction loss functions like Structural Similarity Index (SSIM) for better perceptual quality.
Integrate the custom_loss into your VAE model accordingly.
By following the above steps, you should be able to implement and experiment with various aspects of your VAE across different datasets. Feel free to adjust parameters and architectures to better suit your specific needs and to achieve optimal performance.
If you encounter any issues or have further questions, feel free to ask!