def load_dataset(dataset_path):
"""
Loads and preprocesses the dataset from the specified directory.
Assumes that the dataset directory contains subdirectories for each class,
but for GANs, class labels are not utilized.
"""
# Collect all image file paths
all_image_paths = []
for root, dirs, files in os.walk(dataset_path):
for file in files:
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
all_image_paths.append(os.path.join(root, file))
code
print(f"Total images found: {len(all_image_paths)}")
if len(all_image_paths) == 0:
raise ValueError(f"No images found in the directory {dataset_path}. Please check the path.")
# Create TensorFlow dataset from file paths
path_ds = tf.data.Dataset.from_tensor_slices(all_image_paths)
# Shuffle and preprocess
image_ds = path_ds.shuffle(buffer_size=BUFFER_SIZE, reshuffle_each_iteration=True)
image_ds = image_ds.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE)
image_ds = image_ds.batch(BATCH_SIZE, drop_remainder=True).prefetch(buffer_size=AUTOTUNE)
# Inspect the shape of a single batch
for image_batch in image_ds.take(1):
tf.print("Batch shape:", tf.shape(image_batch))
return image_ds
Assistant
Build the Generator
def build_generator():
model = tf.keras.Sequential()
model.add(layers.Dense(88256, use_bias=False, input_shape=(NOISE_DIM,)))
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
def generate_and_save_images(model, epoch, test_input):
"""
Generates and saves images using the generator model.
"""
# Generate images
predictions = model(test_input, training=False)
code
# Rescale images from [-1,1] to [0,1]
predictions = (predictions + 1.0) / 2.0
# Create a figure to display the images
fig = plt.figure(figsize=(4,4))
for i in range(predictions.shape[0]):
plt.subplot(4,4,i+1)
plt.imshow(predictions[i])
plt.axis('off')
plt.tight_layout()
plt.savefig(f'generated_images_epoch_{epoch:04d}.png')
plt.close()
Training loop
def train(dataset, epochs):
for epoch in range(1, epochs+1):
start = time.time()
code
gen_loss_list = []
disc_loss_list = []
for image_batch in dataset:
g_loss, d_loss = train_step(image_batch)
gen_loss_list.append(g_loss)
disc_loss_list.append(d_loss)
# Produce images for the current epoch
generate_and_save_images(generator, epoch, seed)
# Save the model every 10 epochs
if (epoch) % 10 == 0:
checkpoint.save(file_prefix = checkpoint_prefix)
# Calculate mean losses
mean_gen_loss = tf.reduce_mean(gen_loss_list)
mean_disc_loss = tf.reduce_mean(disc_loss_list)
print (f'Epoch {epoch}, Time: {time.time()-start:.2f} sec | '
f'Gen Loss: {mean_gen_loss:.4f} | Disc Loss: {mean_disc_loss:.4f}')
# Generate after the final epoch
generate_and_save_images(generator, epochs, seed)
To generate new images after training, you can use the following code:
def generate_images_after_training(model, num_images=16):
"""
Generates and displays new images using the trained generator model.
"""
noise = tf.random.normal([num_images, NOISE_DIM])
predictions = model(noise, training=False)
predictions = (predictions + 1.0) / 2.0 # Rescale to [0,1]
code
fig = plt.figure(figsize=(4,4))
for i in range(predictions.shape[0]):
plt.subplot(4,4,i+1)
plt.imshow(predictions[i])
plt.axis('off')
plt.tight_layout()
plt.show()
Example usage:
generate_images_after_training(generator, 16)
results in
Traceback (most recent call last):
File "/home/leo/Documents/vsc/just a script.py", line 231, in
train(train_dataset, EPOCHS)
File "/home/leo/Documents/vsc/just a script.py", line 209, in train
g_loss, d_loss = train_step(image_batch)
File "/home/leo/.local/lib/python3.10/site-packages/tensorflow/python/util/traceback_utils.py", line 153, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/tmp/autograph_generated_fileuc8zuc1b.py", line 14, in tf__train_step
fake_output = ag.converted_call(ag__.ld(discriminator), (ag__.ld(generated_images),), dict(training=True), fscope)
File "/home/leo/.local/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 122, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/home/leo/.local/lib/python3.10/site-packages/keras/src/layers/input_spec.py", line 227, in assert_input_compatibility
raise ValueError(
ValueError: in user code:
code
File "/home/leo/Documents/vsc/just a script.py", line 162, in train_step *
fake_output = discriminator(generated_images, training=True)
File "/home/leo/.local/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 122, in error_handler **
raise e.with_traceback(filtered_tb) from None
File "/home/leo/.local/lib/python3.10/site-packages/keras/src/layers/input_spec.py", line 227, in assert_input_compatibility
raise ValueError(
ValueError: Exception encountered when calling Sequential.call().
Input 0 of layer "dense_1" is incompatible with the layer: expected axis -1 of input shape to have value 32768, but received input with shape (128, 8192)
Arguments received by Sequential.call():
• inputs=tf.Tensor(shape=(128, 32, 32, 3), dtype=float32)
• training=True
• mask=None
The error you're encountering is due to a mismatch between the output shape of your Generator and the expected input shape of your Discriminator. Specifically, your Generator is producing images of size 32x32 pixels, while your Discriminator expects images of size 64x64 pixels. This discrepancy causes TensorFlow to raise a ValueError because the layers in the Discriminator aren't receiving data in the shape they were designed to handle.
Detailed Explanation of the Error
Error Message:
code
ValueError: Exception encountered when calling Sequential.call().
Input 0 of layer "dense_1" is incompatible with the layer: expected axis -1 of input shape to have value 32768, but received input with shape (128, 8192)
Cause:
The Discriminator expects input images of shape (64, 64, 3).
The Generator is producing images of shape (32, 32, 3).
When these (32, 32, 3) images are fed into the Discriminator, the dimensions don't align with what the Discriminator's layers expect, leading to the ValueError.
Solution: Adjust the Generator to Produce 64x64 Images
To resolve this issue, you need to modify your Generator's architecture so that it outputs images of size 64x64x3 instead of 32x32x3. This can be achieved by adding another Conv2DTranspose layer to further upsample the images.
Step-by-Step Fix
Understand the Current Generator Architecture:
Your current Generator architecture upscales the image as follows:
Dense Layer: Outputs a vector that is reshaped to (8, 8, 256).
Conv2DTranspose (Stride 1): Keeps the spatial dimensions at (8, 8) but reduces channels to 128.
Conv2DTranspose (Stride 2): Upscales to (16, 16) with 64 channels.
Conv2DTranspose (Stride 2): Upscales to (32, 32) with 3 channels.
Modify the Generator to Achieve 64x64 Output:
To reach the desired (64, 64, 3) output, add another Conv2DTranspose layer that doubles the spatial dimensions from (32, 32) to (64, 64).
With the updated Generator, you can proceed to train your model. The Discriminator should now receive images of shape (64, 64, 3), matching its expected input shape.
Additional Recommendations:
Monitor Training: Keep an eye on the training process to ensure that both the Generator and Discriminator are learning effectively. Adjust hyperparameters like learning rates, batch size, or network depth if necessary.
Checkpointing and Saving Models: Ensure that model checkpoints are being saved correctly, especially after significant training milestones.
Visualization: Continue generating and saving images after each epoch to monitor the Generator's progress visually.
Complete Revised Generator Function
Here is the complete updated build_generator function for clarity:
Adjusting the Generator to produce images that match the expected input shape of the Discriminator is crucial for the successful training of a GAN. By ensuring that both models are compatible in terms of data dimensions, you can eliminate shape-related errors and focus on optimizing the performance of your GAN.
If you encounter any further issues or have additional questions, feel free to ask!
Intermediate Channels: Reduced the number of filters progressively to balance the model's capacity and computational efficiency.
Final Activation: The last layer uses the tanh activation function to output pixel values in the range [-1, 1], matching the normalization applied to your dataset.