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(local_extract_path):
os.makedirs(local_extract_path)
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!")
from sklearn.model_selection import train_test_split
Path to CelebA images
celeba_path = '/content/images/image' # Update this path as needed
def build_conv_encoder(input_shape, latent_dim):
input_img = Input(shape=input_shape)
x = Conv2D(32, kernel_size=3, strides=2, activation='relu', padding='same')(input_img)
x = Conv2D(64, kernel_size=3, strides=2, activation='relu', padding='same')(x)
x_shape = tf.keras.backend.int_shape(x)[1:] # Zachowanie kształtu przed spłaszczeniem
x = Flatten()(x)
x = Dense(128, 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(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(64, kernel_size=3, strides=2, activation='relu', padding='same')(x)
x = Conv2DTranspose(32, kernel_size=3, strides=2, activation='relu', padding='same')(x)
# Dostosowanie liczby Warstw Transponowanych w zależności od wymiaru wyjściowego
# Oblicz aktualny rozmiar po upsamplingu
current_size = x_shape[0] * 2**2 # Podwojeniamy dwa razy
target_size = output_shape[0]
while current_size < target_size:
x = Conv2DTranspose(16, kernel_size=3, strides=1, activation='relu', padding='same')(x)
current_size = current_size # Zmieniamy strides lub inne parametry jeśli potrzebujemy
# Można dostosować, dodając więcej warstw lub zmieniać strides
break # Aby uniknąć nieskończonej pętli, w razie potrzeby dostosuj
outputs = Conv2DTranspose(output_shape[2], kernel_size=3, activation='sigmoid', padding='same')(x)
decoder = Model(latent_inputs, outputs, name='decoder')
return decoder
ValueError: Invalid reduction dimension 3 for input with 3 dimensions. for '{{node Sum}} = Sum[T=DT_FLOAT, Tidx=DT_INT32, keep_dims=false](Mean, Sum/reduction_indices)' with input shapes: [?,64,64], [3] and with computed input tensors: input[1] = <1 2 3>.
The error you're encountering when training your Variational Autoencoder (VAE) on CIFAR-10 and CelebA datasets is:
ValueError: Invalid reduction dimension 3 for input with 3 dimensions. for '{{node Sum}} = Sum[T=DT_FLOAT, Tidx=DT_INT32, keep_dims=false](Mean, Sum/reduction_indices)' with input shapes: [?,32,32], [3] and with computed input tensors: input[1] = <1 2 3>.
This error indicates that the loss function is trying to reduce (sum) over a dimension that doesn't exist in the input tensor. Specifically, it's attempting to sum over the channel dimension (axis=3) in a tensor that only has three dimensions (batch, height, width), which is insufficient for RGB images that should have four dimensions (batch, height, width, channels).
Root Cause Analysis
Reconstruction Output Shape Mismatch:
Grayscale vs. RGB: Your encoder and decoder are designed to handle both grayscale (1 channel) and RGB (3 channels) images. However, during training on RGB datasets (CIFAR-10 and CelebA), the decoder's output might not be correctly producing the expected number of channels, resulting in a shape like [batch, height, width] instead of [batch, height, width, 3].
Loss Function Handling:
Binary Crossentropy for RGB: Using binary_crossentropy for RGB images can be problematic because binary_crossentropy is typically suited for binary or grayscale data. For color images, a different loss function like mean_squared_error (MSE) might be more appropriate.
Steps to Resolve the Issue
Verify the Decoder's Output Shape:
Print Shapes: Modify the train_step method in your VAE class to print the shapes of both data and reconstruction to ensure they match.
def train_step(self, data):
with tf.GradientTape() as tape:
z_mean, z_log_var, z = self.encoder(data)
reconstruction = self.decoder(z)
# Debugging: Print shapes
print("Data shape:", data.shape)
print("Reconstruction shape:", reconstruction.shape)
# Rest of your loss calculation...
Ensure Channels Are Present: Check whether reconstruction has the same number of channels as data. For CIFAR-10 and CelebA, both should have 3 channels.
Adjust the Decoder Architecture:
Final Layer Configuration: Ensure that the final Conv2DTranspose layer in your decoder correctly outputs the desired number of channels.
outputs = Conv2DTranspose(
output_shape[2], # Should be 3 for RGB
kernel_size=3,
activation='sigmoid',
padding='same'
)(x)
Consistency in output_shape: Verify that output_shape[2] correctly reflects the number of channels in your dataset (1 for Fashion MNIST, 3 for CIFAR-10 and CelebA).
Modify the Loss Function:
Use Mean Squared Error (MSE) for RGB Images: Replace binary_crossentropy with mean_squared_error for RGB datasets to better suit the nature of the data.
Alternative Approach: If you prefer to stick with binary_crossentropy, consider using it only for datasets where it makes sense (like grayscale images) and switch to mean_squared_error or another appropriate loss for RGB images.
Ensure Consistent Data Shapes:
Double-Check Data Loading: Make sure that all datasets (especially CelebA) are loaded with the correct shape, including the channel dimension.
# For CelebA
celebA_path = '/content/images/image' # Update this path as needed
def load_celeba_images(path, img_size=(64, 64)):
image_paths = glob.glob(os.path.join(path, '*.jpg'))
images = []
for img_path in image_paths:
img = load_img(img_path, target_size=img_size)
img = img_to_array(img) / 255.0
images.append(img)
return np.array(images)
x_celeba = load_celeba_images(celeba_path)
print(f"x_celeba shape: {x_celeba.shape}") # Should be (num_samples, 64, 64, 3)
Update the Decoder's Upsampling Logic (If Necessary):
Ensure Correct Upsampling: Make sure that after upsampling, the feature maps maintain the correct spatial dimensions corresponding to the original input size.
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(64, kernel_size=3, strides=2, activation='relu', padding='same')(x)
x = Conv2DTranspose(32, kernel_size=3, strides=2, activation='relu', padding='same')(x)
# Calculate current size after upsampling
current_size = x_shape[0] * 2**2 # Adjust based on strides
target_size = output_shape[0]
while current_size < target_size:
x = Conv2DTranspose(16, kernel_size=3, strides=1, activation='relu', padding='same')(x)
current_size += 1 # Adjust as needed
# Remove `break` to allow multiple layers if needed
outputs = Conv2DTranspose(
output_shape[2],
kernel_size=3,
activation='sigmoid',
padding='same'
)(x)
decoder = Model(latent_inputs, outputs, name='decoder')
return decoder
Alternative: Separate Models for Different Datasets:
Simplify by Creating Separate Encoders and Decoders: If managing multiple datasets with varying input shapes and channel counts becomes cumbersome, consider creating separate encoder and decoder architectures tailored to each dataset’s specific requirements.
Example Adjustments
Here's how you can adjust your VAE class and train_vae function to incorporate these changes:
Consistent Data Shapes: Always ensure that your input data and model outputs have consistent shapes, especially regarding the channel dimension.
Appropriate Loss Functions: Use loss functions that align with the nature of your data. For grayscale images, binary_crossentropy is suitable, whereas for RGB images, mean_squared_error or categorical_crossentropy might be more appropriate.
Debugging Aids: Incorporate print statements or use TensorBoard to monitor tensor shapes and values during training. This can help quickly identify mismatches or unexpected behaviors.
Separate Models for Different Datasets: If managing multiple datasets with varying characteristics becomes complex, consider designing separate encoder-decoder architectures optimized for each dataset.
Validation Checks: Before training, add assertions or checks to ensure that the shapes of the training and reconstruction data match.
By implementing these adjustments and recommendations, you should be able to resolve the ValueError and successfully train your VAE on both CIFAR-10 and CelebA datasets.