import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Reshape, Conv2DTranspose, Conv2D, Flatten
from tensorflow.keras.models import Model
from tensorflow.keras.datasets import fashion_mnist
import numpy as np
from tensorflow.keras.layers import Layer
if not os.path.exists(zip_path): # Sprawdzanie, czy plik ZIP już istnieje
print(f"Pobieranie pliku ZIP z Google Drive: {zip_url}...")
gdown.download(zip_url, zip_path, quiet=False)
else:
print(f"Plik ZIP już istnieje: {zip_path}")
Rozpakowanie archiwum
if not os.path.exists(local_extract_path): # Sprawdzanie, czy katalog już istnieje
os.makedirs(local_extract_path) # Tworzenie katalogu, jeśli nie istnieje
print(f"Rozpakowywanie pliku ZIP: {zip_path} do {local_extract_path}...")
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(local_extract_path)
print("Rozpakowywanie zakończone!")
else:
print(f"Katalog docelowy już istnieje: {local_extract_path}")
Assistant
import glob
import os
import zipfile # Dodano moduł zipfile
from sklearn.model_selection import train_test_split
import numpy as np
from tensorflow.keras.preprocessing.image import load_img, img_to_array
Path to CelebA images
celeba_path = '/content/images/image' # Update this path as needed
Pokaż w jaki sposób ulepszyć moje szkolenie, aby model mógł się uczyć bardziej skomplikowanych wzorców
Pamiętaj że różne zbiory danych mają różny shape, co może powodować błąd ValueError: Arguments target and output must have the same shape. Received: target.shape=(None, 28, 28, 1), output.shape=(None, 16, 16, 1), obecny kod który tobie wysyłąm jest poprawny, wypisz cały zoptymalizowany kod
To enhance your Variational Autoencoder (VAE) for learning more complex patterns across different datasets (MNIST, Fashion MNIST, CIFAR-10, and CelebA) and to resolve the ValueError related to shape mismatches, I've optimized your code with the following improvements:
Symmetrical Encoder-Decoder Architecture: Ensured that the encoder and decoder have symmetrical architectures tailored to each dataset's complexity and input shape.
Dynamic Handling of Input Shapes: Removed the loop in the decoder construction and ensured that the decoder precisely reconstructs the input shape by mirroring the encoder layers.
Increased Model Capacity: Added more convolutional layers and increased the number of filters for more complex datasets like CIFAR-10 and CelebA to capture intricate patterns.
Flexible Reconstruction Loss Calculation: Updated the reconstruction loss to dynamically adapt to the number of channels in the input data.
Enhanced Training Visualization: Improved the visualization of training losses and reconstructions for better monitoring.
Batch Normalization: Introduced Batch Normalization layers to stabilize and potentially accelerate training.
Code Modularization: Structured the code into functions for better readability and maintenance.
Below is the complete optimized code with these enhancements:
python
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Reshape, Conv2DTranspose, Conv2D, Flatten, BatchNormalization, LeakyReLU
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
import os
import zipfile
import gdown # Library for downloading files from Google Drive
import glob
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 using reparameterization trick
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
# Encoder builder
def build_conv_encoder(input_shape, latent_dim, num_filters=64, kernel_size=3, strides=2):
input_img = Input(shape=input_shape)
x = Conv2D(num_filters, kernel_size=kernel_size, strides=strides, padding='same')(input_img)
x = BatchNormalization()(x)
x = LeakyReLU()(x)
x = Conv2D(num_filters*2, kernel_size=kernel_size, strides=strides, padding='same')(x)
x = BatchNormalization()(x)
x = LeakyReLU()(x)
x = Conv2D(num_filters*4, kernel_size=kernel_size, strides=1, padding='same')(x)
x = BatchNormalization()(x)
x = LeakyReLU()(x)
shape_before_flattening = tf.keras.backend.int_shape(x)[1:]
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])
encoder = Model(input_img, [z_mean, z_log_var, z], name='encoder')
return encoder, shape_before_flattening
# Decoder builder
def build_conv_decoder(shape_before_flattening, latent_dim, output_shape, num_filters=64, kernel_size=3, strides=2):
latent_inputs = Input(shape=(latent_dim,))
x = Dense(np.prod(shape_before_flattening), activation='relu')(latent_inputs)
x = Reshape(shape_before_flattening)(x)
x = Conv2DTranspose(num_filters*2, kernel_size=kernel_size, strides=strides, padding='same')(x)
x = BatchNormalization()(x)
x = LeakyReLU()(x)
x = Conv2DTranspose(num_filters, kernel_size=kernel_size, strides=strides, padding='same')(x)
x = BatchNormalization()(x)
x = LeakyReLU()(x)
x = Conv2DTranspose(output_shape[-1], kernel_size=kernel_size, activation='sigmoid', padding='same')(x)
decoder = Model(latent_inputs, x, name='decoder')
return decoder
# VAE Model
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
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):
with tf.GradientTape() as tape:
z_mean, z_log_var, z = self.encoder(data)
reconstruction = self.decoder(z)
# Dynamically set reduction axes based on input dimensions
if len(data.shape) == 4:
axes = [1, 2, 3]
else:
axes = [1, 2]
reconstruction_loss = tf.reduce_mean(
tf.reduce_sum(
tf.keras.losses.binary_crossentropy(data, reconstruction),
axis=axes
)
)
kl_loss = -0.5 * tf.reduce_mean(
tf.reduce_sum(
1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var),
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)
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 len(data.shape) == 4:
axes = [1, 2, 3]
else:
axes = [1, 2]
reconstruction_loss = tf.reduce_mean(
tf.reduce_sum(
tf.keras.losses.binary_crossentropy(data, reconstruction),
axis=axes
)
)
kl_loss = -0.5 * tf.reduce_mean(
tf.reduce_sum(
1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var),
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]
# Function to build VAE
def build_vae(input_shape, latent_dim, num_filters=64, kl_weight=1.0):
encoder, shape_before_flattening = build_conv_encoder(input_shape, latent_dim, num_filters=num_filters)
decoder = build_conv_decoder(shape_before_flattening, latent_dim, input_shape, num_filters=num_filters)
vae = VAE(encoder, decoder, kl_weight=kl_weight)
return vae
# Function to plot reconstructions
def plot_reconstructions(x_original, x_reconstructed, input_shape, num_images=10, title='Reconstructions'):
plt.figure(figsize=(20, 4))
for i in range(num_images):
# Original images
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 images
ax = plt.subplot(2, num_images, i + 1 + num_images)
if input_shape[-1] == 1:
plt.imshow(x_reconstructed[i].squeeze(), cmap='gray')
else:
plt.imshow(x_reconstructed[i])
ax.axis('off')
plt.suptitle(title)
plt.tight_layout()
plt.show()
# Function to train VAE
def train_vae(vae, x_train, x_val, epochs=30, batch_size=128, dataset_name='Dataset'):
vae.compile(optimizer='adam')
history = vae.fit(
x_train,
epochs=epochs,
batch_size=batch_size,
validation_data=(x_val, x_val)
)
# Plot training & validation loss
plt.figure(figsize=(8,6))
plt.plot(history.history['loss'], label='Total Loss')
plt.plot(history.history['reconstruction_loss'], label='Reconstruction Loss')
plt.plot(history.history['val_loss'], label='Val Total Loss')
plt.plot(history.history['val_reconstruction_loss'], label='Val Reconstruction 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])
plot_reconstructions(x_val[:10], x_reconstructed, vae.encoder.input_shape[1:], title=f'Reconstructions on {dataset_name}')
return vae
# Data Loading Functions
def load_mnist_data():
(x_train, _), (x_test, _) = mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = np.expand_dims(x_train, -1) # (60000, 28, 28, 1)
x_test = np.expand_dims(x_test, -1)
return x_train, x_test
def load_fashion_mnist_data():
(x_train, _), (x_test, _) = fashion_mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = np.expand_dims(x_train, -1) # (60000, 28, 28, 1)
x_test = np.expand_dims(x_test, -1)
return x_train, x_test
def load_cifar10_data():
(x_train, _), (x_test, _) = cifar10.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
return x_train, x_test
def download_and_load_celeba(zip_url, zip_path, extract_path, img_size=(64,64), max_images=None):
import gdown
if not os.path.exists(zip_path):
print(f"Downloading CelebA dataset from: {zip_url}")
gdown.download(zip_url, zip_path, quiet=False)
else:
print(f"CelebA ZIP already exists at: {zip_path}")
if not os.path.exists(extract_path):
os.makedirs(extract_path)
print(f"Extracting CelebA dataset to: {extract_path}")
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(extract_path)
print("Extraction completed.")
else:
print(f"CelebA dataset already extracted at: {extract_path}")
# Load images
image_paths = glob.glob(os.path.join(extract_path, '*.jpg'))
if max_images:
image_paths = image_paths[:max_images]
images = []
for img_path in image_paths:
img = load_img(img_path, target_size=img_size)
img = img_to_array(img) / 255.
images.append(img)
x_celeba = np.array(images)
return x_celeba
# Main Execution
def main():
# Load Datasets
print("Loading MNIST data...")
x_train_mnist, x_test_mnist = load_mnist_data()
print(f"x_train_mnist shape: {x_train_mnist.shape}")
print(f"x_test_mnist shape: {x_test_mnist.shape}\n")
print("Loading Fashion MNIST data...")
x_train_fashion, x_test_fashion = load_fashion_mnist_data()
print(f"x_train_fashion shape: {x_train_fashion.shape}")
print(f"x_test_fashion shape: {x_test_fashion.shape}\n")
print("Loading CIFAR-10 data...")
x_train_cifar, x_test_cifar = load_cifar10_data()
print(f"x_train_cifar shape: {x_train_cifar.shape}")
print(f"x_test_cifar shape: {x_test_cifar.shape}\n")
# Download and Load CelebA Dataset
celeba_file_id = '1A2dNWabg6_um-V3lhw1tyead5hCpjaW8' # Update with correct file ID
celeba_zip_url = f'https://drive.google.com/uc?id={celeba_file_id}'
celeba_zip_path = '/content/image.zip'
celeba_extract_path = '/content/images'
print("Downloading and loading CelebA data...")
x_celeba = download_and_load_celeba(celeba_zip_url, celeba_zip_path, celeba_extract_path, img_size=(64,64), max_images=30000)
print(f"x_celeba shape: {x_celeba.shape}\n")
# Split CelebA into training and validation
x_train_celeba, x_val_celeba = train_test_split(x_celeba, test_size=0.3, random_state=321565)
print(f"x_train_celeba shape: {x_train_celeba.shape}")
print(f"x_val_celeba shape: {x_val_celeba.shape}\n")
# Training on Fashion MNIST
print("Training VAE on Fashion MNIST...")
vae_fashion = build_vae(input_shape=(28, 28, 1), latent_dim=16, num_filters=64, kl_weight=0.1)
vae_fashion = train_vae(
vae=vae_fashion,
x_train=x_train_fashion,
x_val=x_test_fashion,
epochs=30,
batch_size=128,
dataset_name='Fashion MNIST'
)
# Training on CIFAR-10
print("Training VAE on CIFAR-10...")
vae_cifar = build_vae(input_shape=(32, 32, 3), latent_dim=32, num_filters=128, kl_weight=0.1)
vae_cifar = train_vae(
vae=vae_cifar,
x_train=x_train_cifar,
x_val=x_test_cifar,
epochs=30,
batch_size=256,
dataset_name='CIFAR-10'
)
# Training on CelebA
print("Training VAE on CelebA...")
vae_celeba = build_vae(input_shape=(64, 64, 3), latent_dim=64, num_filters=256, kl_weight=0.1)
vae_celeba = train_vae(
vae=vae_celeba,
x_train=x_train_celeba,
x_val=x_val_celeba,
epochs=30,
batch_size=128,
dataset_name='CelebA'
)
if __name__ == "__main__":
main()
Explanation of Optimizations
Encoder and Decoder Enhancements:
Batch Normalization: Added BatchNormalization layers after each convolutional layer in both encoder and decoder to stabilize and accelerate training.
Activation Functions: Replaced ReLU with LeakyReLU to mitigate the "dying ReLU" problem and allow a small gradient when the unit is not active.
Increased Filters: For more complex datasets like CIFAR-10 and CelebA, increased the number of filters to 128 and 256 respectively to capture more intricate features.
Removed Loop in Decoder: Eliminated the while-loop in the decoder construction to ensure that the output shape strictly matches the input shape by mirroring the encoder layers.
Flexible Reconstruction Loss:
Updated the loss calculation to dynamically determine the axes to sum over based on the input shape. This ensures compatibility across grayscale and RGB images.
VAE Class Improvements:
Dynamic Batch Shape Handling: The VAE class now correctly identifies whether the input is grayscale or RGB and adjusts the loss calculation accordingly.
Metrics Tracking: Enhanced metrics to include both training and validation losses for better monitoring.
Training Function Enhancements:
Visualization: Improved the plotting functions to clearly display both training and validation losses, as well as the reconstruction results.
Consistent Validation Data: Changed validation_data to (x_val, x_val) to align with the unsupervised nature of VAEs.
Data Handling:
Data Loading Modularization: Separated data loading into distinct functions for better organization and scalability.
CelebA Dataset Handling: Added a function to download, extract, and preprocess the CelebA dataset efficiently.
Main Function:
Structured the code into a main function to sequentially load data, build VAEs with appropriate configurations, and train them on each dataset.
Notes
CelebA Dataset: Ensure that the file_id for the CelebA dataset is correct. Replace '1A2dNWabg6_um-V3lhw1tyead5hCpjaW8' with the actual file ID if it's different.
Computational Resources: Training VAEs, especially on complex datasets like CelebA, may require substantial computational resources (preferably GPUs). Ensure that your environment is equipped accordingly.
Hyperparameter Tuning: The current architecture uses specific hyperparameters (e.g., latent dimensions, number of filters). Depending on the results, you might want to experiment with these values for optimal performance.
This optimized code should resolve the shape mismatch errors and provide a more robust framework for training VAEs on diverse datasets. Feel free to further tweak the architecture and hyperparameters based on your specific requirements and observations during training.