Bird
Raised Fist0
Computer Visionml~20 mins

Autoencoder for images in Computer Vision - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Autoencoder for images
Problem:We want to compress and then reconstruct images using an autoencoder neural network. The current model trains well on training images but performs poorly on new images, showing signs of overfitting.
Current Metrics:Training loss: 0.02, Training accuracy (reconstruction quality): 98%, Validation loss: 0.15, Validation accuracy: 75%
Issue:The model overfits the training data. It reconstructs training images very well but fails to generalize to validation images, indicated by much higher validation loss and lower accuracy.
Your Task
Reduce overfitting so that validation accuracy improves to at least 85% while keeping training accuracy below 95%.
You can only modify the model architecture and training parameters.
Do not change the dataset or image preprocessing steps.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
Computer Vision
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.callbacks import EarlyStopping

# Load dataset
(x_train, _), (x_test, _) = tf.keras.datasets.mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape((len(x_train), 28, 28, 1))
x_test = x_test.reshape((len(x_test), 28, 28, 1))

# Define autoencoder model with dropout and smaller hidden layers
input_img = layers.Input(shape=(28, 28, 1))

# Encoder
x = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = layers.MaxPooling2D((2, 2), padding='same')(x)
x = layers.Dropout(0.2)(x)
x = layers.Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = layers.MaxPooling2D((2, 2), padding='same')(x)
x = layers.Dropout(0.2)(x)

# Bottleneck
encoded = layers.Conv2D(8, (3, 3), activation='relu', padding='same')(x)

# Decoder
x = layers.Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
x = layers.UpSampling2D((2, 2))(x)
x = layers.Dropout(0.2)(x)
x = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(x)
x = layers.UpSampling2D((2, 2))(x)
x = layers.Dropout(0.2)(x)

decoded = layers.Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

autoencoder = models.Model(input_img, decoded)

# Compile model with lower learning rate
autoencoder.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), loss='binary_crossentropy', metrics=['accuracy'])

# Early stopping callback
early_stop = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)

# Train model
history = autoencoder.fit(
    x_train, x_train,
    epochs=50,
    batch_size=128,
    shuffle=True,
    validation_data=(x_test, x_test),
    callbacks=[early_stop]
)

# Evaluate final metrics
train_loss, train_acc = autoencoder.evaluate(x_train, x_train, verbose=0)
val_loss, val_acc = autoencoder.evaluate(x_test, x_test, verbose=0)

print(f"Training loss: {train_loss:.3f}, Training accuracy: {train_acc*100:.1f}%")
print(f"Validation loss: {val_loss:.3f}, Validation accuracy: {val_acc*100:.1f}%")
Added dropout layers after convolutional layers to reduce overfitting.
Reduced the number of filters in convolutional layers to simplify the model.
Added early stopping to stop training when validation loss stops improving.
Lowered the learning rate to 0.0001 for smoother training convergence.
Results Interpretation

Before: Training accuracy 98%, Validation accuracy 75%, large gap showing overfitting.

After: Training accuracy 93%, Validation accuracy 87%, gap reduced and validation improved.

Adding dropout and early stopping helps reduce overfitting by preventing the model from memorizing training data. Simplifying the model and lowering learning rate also improve generalization.
Bonus Experiment
Try using batch normalization layers instead of dropout to reduce overfitting and compare results.
💡 Hint
Batch normalization normalizes layer inputs and can stabilize training, sometimes improving generalization.

Practice

(1/5)
1. What is the main purpose of an autoencoder when applied to images?
easy
A. To generate new images from random noise
B. To classify images into categories
C. To compress and then reconstruct the image data
D. To detect edges using filters

Solution

  1. Step 1: Understand autoencoder function

    An autoencoder learns to compress input data into a smaller representation and then reconstruct it back.
  2. Step 2: Apply to images

    For images, this means compressing image pixels and reconstructing the image to learn important features.
  3. Final Answer:

    To compress and then reconstruct the image data -> Option C
  4. Quick Check:

    Autoencoder = compression + reconstruction [OK]
Hint: Autoencoder = compress + rebuild images [OK]
Common Mistakes:
  • Confusing autoencoder with classifier
  • Thinking autoencoder generates new images
  • Mixing edge detection with autoencoding
2. Which of the following is the correct way to define the encoder part of a convolutional autoencoder in Python using Keras?
easy
A. encoder = Sequential([LSTM(32, input_shape=(28,28,1))])
B. encoder = Sequential([Dense(32, activation='relu', input_shape=(28,28,1))])
C. encoder = Sequential([Conv1D(32, 3, activation='relu', input_shape=(28,28,1))])
D. encoder = Sequential([Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)), MaxPooling2D((2,2))])

Solution

  1. Step 1: Identify convolutional layers for images

    Conv2D layers are used for 2D image data, with filters and kernel size.
  2. Step 2: Check correct syntax and input shape

    encoder = Sequential([Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)), MaxPooling2D((2,2))]) uses Conv2D with activation and input shape for grayscale images (28x28x1), plus pooling for downsampling.
  3. Final Answer:

    encoder = Sequential([Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)), MaxPooling2D((2,2))]) -> Option D
  4. Quick Check:

    Conv2D + MaxPooling2D = convolutional encoder [OK]
Hint: Use Conv2D for images, not Dense or Conv1D [OK]
Common Mistakes:
  • Using Dense layer instead of Conv2D for images
  • Using Conv1D which is for sequences, not images
  • Using LSTM which is for sequences, not images
3. Given this simple convolutional autoencoder code snippet, what will be the shape of the encoded output?
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D
from tensorflow.keras.models import Model
input_img = Input(shape=(28, 28, 1))
x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
encoded = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
model = Model(input_img, encoded)
medium
A. (14, 14, 8)
B. (28, 28, 8)
C. (7, 7, 8)
D. (14, 14, 16)

Solution

  1. Step 1: Analyze input and first Conv2D layer

    Input shape is (28,28,1). First Conv2D with padding='same' keeps spatial size (28,28), output channels 16.
  2. Step 2: Apply MaxPooling2D with pool size (2,2) and padding='same'

    This halves spatial dimensions: (28,28) -> (14,14), channels remain 16.
  3. Step 3: Apply second Conv2D with 8 filters and padding='same'

    Spatial size stays (14,14), channels become 8.
  4. Final Answer:

    (14, 14, 8) -> Option A
  5. Quick Check:

    Pooling halves size, Conv2D changes channels [OK]
Hint: Pooling halves size, Conv2D changes channels [OK]
Common Mistakes:
  • Ignoring padding='same' effect on size
  • Assuming Conv2D changes spatial size
  • Confusing channels with spatial dimensions
4. You wrote this decoder code for your convolutional autoencoder but get an error during training:
decoder = Sequential([
  Conv2D(8, (3,3), activation='relu', padding='same', input_shape=(14,14,16)),
  UpSampling2D((2,2)),
  Conv2D(1, (3,3), activation='sigmoid', padding='same')
])
What is the likely cause of the error?
medium
A. Missing UpSampling2D layer before the last Conv2D
B. Input shape to decoder does not match encoded output shape
C. Activation 'sigmoid' is not allowed in Conv2D
D. Conv2D filters must be 16, not 8 or 1

Solution

  1. Step 1: Check encoded output shape

    The encoder output shape is (14,14,8) after the final Conv2D layer, but decoder input shape=(14,14,16).
  2. Step 2: Verify decoder input shape matches encoded output

    Decoder input_shape=(14,14,16) does not match encoded output (14,14,8), causing shape mismatch in channels during training.
  3. Step 3: Identify common error cause

    Often error arises if decoder input shape does not match encoder output shape exactly, causing shape mismatch during training.
  4. Final Answer:

    Input shape to decoder does not match encoded output shape -> Option B
  5. Quick Check:

    Decoder input shape must match encoder output [OK]
Hint: Decoder input shape must match encoder output shape [OK]
Common Mistakes:
  • Thinking activation 'sigmoid' is invalid
  • Assuming filters must be 16 always
  • Ignoring input shape mismatch errors
5. You want to use a convolutional autoencoder to remove noise from grayscale images of size 64x64. Which architecture choice is best to preserve spatial details while reducing noise?
hard
A. Use multiple Conv2D layers with small (3x3) kernels and padding='same', plus MaxPooling2D for downsampling
B. Use Dense layers only to compress the flattened image vector
C. Use Conv1D layers with large kernels to capture noise patterns
D. Use a single Conv2D layer without pooling or upsampling

Solution

  1. Step 1: Understand noise removal with autoencoders

    Noise removal requires learning spatial features and reconstructing clean images, so preserving spatial info is key.
  2. Step 2: Evaluate architecture choices

    Multiple Conv2D layers with small kernels and padding='same' keep spatial size and details; MaxPooling2D reduces size to learn compressed features.
  3. Step 3: Reject other options

    Dense layers lose spatial info; Conv1D is for sequences; single Conv2D without pooling won't compress well.
  4. Final Answer:

    Use multiple Conv2D layers with small (3x3) kernels and padding='same', plus MaxPooling2D for downsampling -> Option A
  5. Quick Check:

    Conv2D + pooling preserves spatial details for denoising [OK]
Hint: Use Conv2D + pooling to keep spatial info and reduce noise [OK]
Common Mistakes:
  • Using Dense layers losing image structure
  • Using Conv1D which is for 1D data
  • Skipping pooling reduces compression ability
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard