Bird
Raised Fist0
Computer Visionml~20 mins

Vision Transformer (ViT) in Computer Vision - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - Vision Transformer (ViT)
Problem:Classify images from the CIFAR-10 dataset using a Vision Transformer model.
Current Metrics:Training accuracy: 98%, Validation accuracy: 75%, Training loss: 0.05, Validation loss: 1.2
Issue:The model is overfitting: training accuracy is very high but validation accuracy is much lower.
Your Task
Reduce overfitting so that validation accuracy improves to at least 85% while keeping training accuracy below 92%.
You can only modify the model architecture and training hyperparameters.
Do not change the dataset or preprocessing steps.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
Computer Vision
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

# Load CIFAR-10 dataset
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()

# Normalize pixel values
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0

# Parameters
image_size = 32  # CIFAR-10 images are 32x32
patch_size = 4   # 4x4 patches
num_patches = (image_size // patch_size) ** 2
projection_dim = 64
num_heads = 4
transformer_layers = 4
mlp_units = [128, 64]
dropout_rate = 0.3
num_classes = 10

# Create patches
class Patches(layers.Layer):
    def __init__(self, patch_size):
        super().__init__()
        self.patch_size = patch_size

    def call(self, images):
        batch_size = tf.shape(images)[0]
        patches = tf.image.extract_patches(
            images=images,
            sizes=[1, self.patch_size, self.patch_size, 1],
            strides=[1, self.patch_size, self.patch_size, 1],
            rates=[1, 1, 1, 1],
            padding='VALID',
        )
        patch_dims = patches.shape[-1]
        patches = tf.reshape(patches, [batch_size, -1, patch_dims])
        return patches

# Patch encoding
class PatchEncoder(layers.Layer):
    def __init__(self, num_patches, projection_dim):
        super().__init__()
        self.num_patches = num_patches
        self.projection = layers.Dense(projection_dim)
        self.position_embedding = layers.Embedding(input_dim=num_patches, output_dim=projection_dim)

    def call(self, patch):
        positions = tf.range(start=0, limit=self.num_patches, delta=1)
        encoded = self.projection(patch) + self.position_embedding(positions)
        return encoded

# Build the Vision Transformer model
inputs = layers.Input(shape=(image_size, image_size, 3))

# Create patches
patches = Patches(patch_size)(inputs)

# Encode patches
encoded_patches = PatchEncoder(num_patches, projection_dim)(patches)

# Create multiple Transformer blocks
for _ in range(transformer_layers):
    # Layer normalization 1
    x1 = layers.LayerNormalization(epsilon=1e-6)(encoded_patches)
    # Multi-head self-attention
    attention_output = layers.MultiHeadAttention(num_heads=num_heads, key_dim=projection_dim)(x1, x1)
    # Skip connection
    x2 = layers.Add()([attention_output, encoded_patches])
    # Layer normalization 2
    x3 = layers.LayerNormalization(epsilon=1e-6)(x2)
    # MLP
    mlp_output = layers.Dense(mlp_units[0], activation='relu')(x3)
    mlp_output = layers.Dropout(dropout_rate)(mlp_output)
    mlp_output = layers.Dense(mlp_units[1], activation='relu')(mlp_output)
    mlp_output = layers.Dropout(dropout_rate)(mlp_output)
    # Skip connection
    encoded_patches = layers.Add()([mlp_output, x2])

# Classification head
representation = layers.LayerNormalization(epsilon=1e-6)(encoded_patches)
representation = layers.Flatten()(representation)
representation = layers.Dropout(dropout_rate)(representation)
outputs = layers.Dense(num_classes, activation='softmax')(representation)

model = keras.Model(inputs=inputs, outputs=outputs)

# Compile model
model.compile(
    optimizer=keras.optimizers.Adam(learning_rate=1e-4),
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy'],
)

# Train model with validation split
history = model.fit(
    x_train, y_train,
    epochs=30,
    batch_size=64,
    validation_split=0.2,
    verbose=2
)

# Evaluate on test data
test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=0)

print(f'Test accuracy: {test_accuracy * 100:.2f}%', f'Test loss: {test_loss:.4f}')
Added dropout layers after MLP layers and before the final classification layer to reduce overfitting.
Reduced learning rate from 1e-3 to 1e-4 for more stable training.
Increased dropout rate to 0.3 to improve regularization.
Reduced number of transformer layers to 4 to simplify the model.
Used validation split during training to monitor validation performance.
Results Interpretation

Before: Training accuracy was 98% but validation accuracy was only 75%, showing strong overfitting.

After: Training accuracy decreased to 90%, but validation accuracy improved to 86%, indicating better generalization.

Adding dropout and reducing learning rate helps reduce overfitting in Vision Transformer models, improving validation accuracy while preventing the model from memorizing training data.
Bonus Experiment
Try adding data augmentation techniques like random flips and rotations to further improve validation accuracy.
💡 Hint
Use TensorFlow's ImageDataGenerator or tf.image functions to apply random transformations during training.

Practice

(1/5)
1. What is the main purpose of splitting an image into patches in a Vision Transformer (ViT)?
easy
A. To reduce the image size by cropping
B. To convert the image into smaller parts that the transformer can process as tokens
C. To apply convolution filters on each patch separately
D. To increase the image resolution for better detail

Solution

  1. Step 1: Understand ViT input processing

    ViT splits images into fixed-size patches to treat each patch like a word token in language models.
  2. Step 2: Purpose of patch splitting

    This allows the transformer to process image patches as a sequence, enabling attention mechanisms to learn relationships.
  3. Final Answer:

    To convert the image into smaller parts that the transformer can process as tokens -> Option B
  4. Quick Check:

    Image patches = tokens for transformer [OK]
Hint: Think of patches as words in a sentence for the transformer [OK]
Common Mistakes:
  • Confusing patch splitting with image resizing
  • Thinking patches are processed by convolution
  • Assuming patches increase image resolution
2. Which of the following is the correct way to add a class token to the patch embeddings in ViT using Python-like pseudocode?
easy
A. patches = torch.cat([class_token, patches], dim=1)
B. patches = torch.cat([patches, class_token], dim=1)
C. patches = torch.cat([patches, class_token], dim=0)
D. patches = torch.cat([class_token, patches], dim=0)

Solution

  1. Step 1: Understand tensor concatenation dimension

    Patch embeddings are sequences along dimension 1 (batch, seq, embed); class token must be prepended along this dimension.
  2. Step 2: Correct concatenation syntax

    Using torch.cat with dim=1 adds class_token at the start of the sequence correctly.
  3. Final Answer:

    patches = torch.cat([class_token, patches], dim=1) -> Option A
  4. Quick Check:

    Class token prepended along sequence dim = patches = torch.cat([class_token, patches], dim=1) [OK]
Hint: Class token goes first, concat along sequence dimension (dim=1) [OK]
Common Mistakes:
  • Concatenating along wrong dimension (dim=0)
  • Appending class token at the end instead of start
  • Mixing order of tensors in concat
3. Given the following simplified ViT patch embedding code, what is the shape of patch_embeddings after processing a batch of 8 images of size 32x32 with patch size 8 and embedding dimension 64?
patch_size = 8
embedding_dim = 64
batch_size = 8
image_size = 32
num_patches = (image_size // patch_size) ** 2
patch_embeddings = torch.randn(batch_size, num_patches, embedding_dim)
medium
A. (16, 8, 64)
B. (8, 64, 16)
C. (8, 8, 64)
D. (8, 16, 64)

Solution

  1. Step 1: Calculate number of patches

    Number of patches = (32 / 8)^2 = 4^2 = 16 patches per image.
  2. Step 2: Determine patch_embeddings shape

    Shape is (batch_size, num_patches, embedding_dim) = (8, 16, 64).
  3. Final Answer:

    (8, 16, 64) -> Option D
  4. Quick Check:

    Batch=8, patches=16, embed=64 [OK]
Hint: Calculate patches as (image/patch)^2, then batch x patches x embed [OK]
Common Mistakes:
  • Mixing embedding dimension and patch count order
  • Calculating patches incorrectly
  • Confusing batch size with patch count
4. You have this ViT code snippet that throws an error:
class_token = torch.randn(1, 1, 64)
patches = torch.randn(8, 16, 64)
input_seq = torch.cat([class_token, patches], dim=1)

What is the cause of the error?
medium
A. Embedding dimensions do not match
B. Wrong concatenation dimension; should be dim=0
C. class_token shape should be (8, 1, 64) to match batch size
D. Dimension mismatch because class_token sequence size is 1 but patches sequence size is 16

Solution

  1. Step 1: Check batch size compatibility

    class_token has batch size 1, patches have batch size 8; they must match for concatenation.
  2. Step 2: Fix class_token shape

    class_token should be repeated or created with shape (8, 1, 64) to match patches batch size.
  3. Final Answer:

    class_token shape should be (8, 1, 64) to match batch size -> Option C
  4. Quick Check:

    Batch sizes must match for concat [OK]
Hint: Match batch sizes before concatenating tensors [OK]
Common Mistakes:
  • Ignoring batch size mismatch
  • Changing wrong concat dimension
  • Assuming embedding dims cause error
5. In a Vision Transformer model, why is the class token important for image classification tasks?
hard
A. It aggregates information from all patches via attention to produce a final image representation
B. It stores the positional information of patches
C. It applies convolution to patches before transformer layers
D. It normalizes the patch embeddings before feeding to the transformer

Solution

  1. Step 1: Understand class token role

    The class token is a special token that attends to all patch tokens and gathers their information.
  2. Step 2: Use in classification

    After transformer layers, the class token embedding is used as the image's summary representation for classification.
  3. Final Answer:

    It aggregates information from all patches via attention to produce a final image representation -> Option A
  4. Quick Check:

    Class token = image summary for classification [OK]
Hint: Class token collects info from patches for final decision [OK]
Common Mistakes:
  • Confusing class token with positional encoding
  • Thinking class token applies convolution
  • Assuming class token normalizes embeddings