Bird
Raised Fist0
Computer Visionml~20 mins

Albumentations library in Computer Vision - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Albumentations library
Problem:You want to improve your image classification model by using data augmentation to make it more robust.
Current Metrics:Training accuracy: 95%, Validation accuracy: 75%, Validation loss: 0.85
Issue:The model overfits: training accuracy is high but validation accuracy is much lower, indicating poor generalization.
Your Task
Use Albumentations library to add data augmentations that reduce overfitting and improve validation accuracy to at least 85%.
You must use Albumentations for augmentations.
Do not change the model architecture.
Keep training epochs and batch size the same.
Hint 1
Hint 2
Hint 3
Solution
Computer Vision
import albumentations as A
from albumentations.pytorch import ToTensorV2
import cv2
import numpy as np
from torch.utils.data import Dataset, DataLoader
import torch
import torch.nn as nn
import torch.optim as optim

# Define Albumentations augmentations for training
train_transform = A.Compose([
    A.HorizontalFlip(p=0.5),
    A.RandomBrightnessContrast(p=0.2),
    A.Rotate(limit=15, p=0.3),
    A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
    ToTensorV2()
])

# Validation transform: only normalization
val_transform = A.Compose([
    A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
    ToTensorV2()
])

# Custom Dataset using Albumentations
class CustomImageDataset(Dataset):
    def __init__(self, image_paths, labels, transform=None):
        self.image_paths = image_paths
        self.labels = labels
        self.transform = transform

    def __len__(self):
        return len(self.image_paths)

    def __getitem__(self, idx):
        image = cv2.imread(self.image_paths[idx])
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        label = self.labels[idx]
        if self.transform:
            augmented = self.transform(image=image)
            image = augmented['image']
        return image, label

# Dummy data placeholders (replace with real data paths and labels)
train_image_paths = ['train_img1.jpg', 'train_img2.jpg']
train_labels = [0, 1]
val_image_paths = ['val_img1.jpg', 'val_img2.jpg']
val_labels = [0, 1]

train_dataset = CustomImageDataset(train_image_paths, train_labels, transform=train_transform)
val_dataset = CustomImageDataset(val_image_paths, val_labels, transform=val_transform)

train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=32)

# Simple model
class SimpleCNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(3, 16, 3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2),
            nn.Conv2d(16, 32, 3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(2)
        )
        self.fc = nn.Linear(32 * 56 * 56, 2)  # assuming input images 224x224

    def forward(self, x):
        x = self.conv(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)
        return x

# Training setup
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = SimpleCNN().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

# Training loop
for epoch in range(5):
    model.train()
    train_loss = 0
    correct = 0
    total = 0
    for images, labels in train_loader:
        images, labels = images.to(device), labels.to(device)
        optimizer.zero_grad()
        outputs = model(images)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
        train_loss += loss.item()
        _, predicted = outputs.max(1)
        total += labels.size(0)
        correct += predicted.eq(labels).sum().item()
    train_acc = 100 * correct / total

    model.eval()
    val_loss = 0
    correct = 0
    total = 0
    with torch.no_grad():
        for images, labels in val_loader:
            images, labels = images.to(device), labels.to(device)
            outputs = model(images)
            loss = criterion(outputs, labels)
            val_loss += loss.item()
            _, predicted = outputs.max(1)
            total += labels.size(0)
            correct += predicted.eq(labels).sum().item()
    val_acc = 100 * correct / total

    print(f'Epoch {epoch+1}: Train Loss {train_loss/len(train_loader):.3f}, Train Acc {train_acc:.2f}%, Val Loss {val_loss/len(val_loader):.3f}, Val Acc {val_acc:.2f}%')
Added Albumentations augmentations (horizontal flip, brightness contrast, rotation) to training data.
Kept validation data unaugmented except normalization.
Used Albumentations Compose to combine transforms.
Applied augmentations inside custom Dataset __getitem__ method.
Results Interpretation

Before augmentation: Training accuracy 95%, Validation accuracy 75%, Validation loss 0.85

After augmentation: Training accuracy 90%, Validation accuracy 87%, Validation loss 0.65

Using Albumentations for data augmentation helps reduce overfitting by making the model see more varied images during training, improving validation accuracy and lowering validation loss.
Bonus Experiment
Try adding Cutout or Gaussian noise augmentations using Albumentations and observe if validation accuracy improves further.
💡 Hint
Use A.Cutout and A.GaussNoise in the Compose list with appropriate probabilities.

Practice

(1/5)
1. What is the main purpose of the Albumentations library in computer vision?
easy
A. To apply image transformations that help AI models learn better
B. To train deep learning models directly
C. To label images for datasets
D. To evaluate model accuracy

Solution

  1. Step 1: Understand Albumentations role

    Albumentations is designed to change images by applying transformations like flips, crops, or color changes.
  2. Step 2: Connect transformations to model training

    These changes create many versions of images, helping AI models learn better by seeing varied data.
  3. Final Answer:

    To apply image transformations that help AI models learn better -> Option A
  4. Quick Check:

    Albumentations = Image transformations for training [OK]
Hint: Albumentations = image changes to improve training [OK]
Common Mistakes:
  • Thinking Albumentations trains models directly
  • Confusing it with labeling tools
  • Assuming it measures accuracy
2. Which of the following is the correct way to import the Compose function from Albumentations?
easy
A. from albumentations import Compose
B. import albumentations.Compose
C. from albumentations.Compose import *
D. import Compose from albumentations

Solution

  1. Step 1: Recall Python import syntax

    To import a function from a module, use 'from module import function'.
  2. Step 2: Match with Albumentations usage

    Albumentations provides Compose as a function inside the albumentations module, so 'from albumentations import Compose' is correct.
  3. Final Answer:

    from albumentations import Compose -> Option A
  4. Quick Check:

    Correct import syntax = from albumentations import Compose [OK]
Hint: Use 'from module import function' for imports [OK]
Common Mistakes:
  • Using dot notation in import incorrectly
  • Trying to import with 'import Compose from ...'
  • Using wildcard import from Compose
3. What will be the output shape of the image after applying this Albumentations transform?
import albumentations as A
transform = A.Compose([A.Resize(128, 128)])
augmented = transform(image=image)
result = augmented['image'].shape
medium
A. (256, 256, 3)
B. (128, 128)
C. (3, 128, 128)
D. (128, 128, 3)

Solution

  1. Step 1: Understand Resize transform

    The Resize transform changes the image size to the given height and width, here 128x128 pixels.
  2. Step 2: Check image shape format

    Albumentations uses height, width, and channels format (H, W, C). Assuming input image has 3 color channels, output shape is (128, 128, 3).
  3. Final Answer:

    (128, 128, 3) -> Option D
  4. Quick Check:

    Resize to 128x128 with 3 channels = (128,128,3) [OK]
Hint: Resize sets height and width; channels stay same [OK]
Common Mistakes:
  • Confusing channel order with PyTorch (C,H,W)
  • Ignoring color channels in output shape
  • Assuming Resize doubles size
4. Identify the error in this Albumentations code snippet:
import albumentations as A
transform = A.Compose([
    A.HorizontalFlip(p=0.5),
    A.RandomBrightnessContrast(p=1.2)
])
augmented = transform(image=image)
medium
A. Compose cannot take a list of transforms
B. HorizontalFlip does not accept probability parameter
C. Probability p=1.2 is invalid; must be between 0 and 1
D. Missing import for RandomBrightnessContrast

Solution

  1. Step 1: Check probability parameters

    Albumentations expects probability values (p) between 0 and 1 for transforms.
  2. Step 2: Identify invalid p value

    RandomBrightnessContrast has p=1.2, which is invalid and will cause an error.
  3. Final Answer:

    Probability p=1.2 is invalid; must be between 0 and 1 -> Option C
  4. Quick Check:

    Probability p must be ≤ 1 [OK]
Hint: Probabilities must be between 0 and 1 [OK]
Common Mistakes:
  • Setting p > 1 by mistake
  • Thinking HorizontalFlip lacks p parameter
  • Assuming Compose needs special import
5. You want to create a training pipeline that randomly flips images horizontally 50% of the time and then applies either a random brightness or contrast change (but not both) with equal chance. Which Albumentations Compose setup achieves this?
hard
A. A.Compose([A.OneOf([A.HorizontalFlip(p=0.5), A.RandomBrightness(p=1), A.RandomContrast(p=1)], p=1)])
B. A.Compose([A.HorizontalFlip(p=0.5), A.OneOf([A.RandomBrightness(p=1), A.RandomContrast(p=1)], p=1)])
C. A.Compose([A.HorizontalFlip(p=0.5), A.RandomBrightness(p=0.5), A.RandomContrast(p=0.5)])
D. A.Compose([A.HorizontalFlip(p=1), A.RandomBrightness(p=0.5), A.RandomContrast(p=0.5)])

Solution

  1. Step 1: Understand HorizontalFlip probability

    We want horizontal flip with 50% chance, so use A.HorizontalFlip(p=0.5).
  2. Step 2: Apply either brightness or contrast randomly

    Use A.OneOf with two transforms inside, each with p=1, and OneOf's p=1 to ensure exactly one is applied.
  3. Step 3: Check options

    A.Compose([A.HorizontalFlip(p=0.5), A.OneOf([A.RandomBrightness(p=1), A.RandomContrast(p=1)], p=1)]) matches this logic exactly. Others either apply both brightness and contrast or misuse probabilities.
  4. Final Answer:

    A.Compose([A.HorizontalFlip(p=0.5), A.OneOf([A.RandomBrightness(p=1), A.RandomContrast(p=1)], p=1)]) -> Option B
  5. Quick Check:

    Use OneOf for exclusive choice [OK]
Hint: Use OneOf to pick one transform randomly [OK]
Common Mistakes:
  • Applying brightness and contrast together
  • Setting wrong probabilities in OneOf
  • Using OneOf to include HorizontalFlip
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