Bird
Raised Fist0
PyTorchml~20 mins

Custom Dataset class in PyTorch - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Custom Dataset class
Problem:You want to train a PyTorch model using your own data stored as images and labels in separate folders. Currently, you do not have a way to load this data efficiently for training.
Current Metrics:No model training yet because data loading is not implemented.
Issue:Without a custom Dataset class, you cannot load and preprocess your own data properly for PyTorch training.
Your Task
Create a PyTorch Custom Dataset class that loads images and their labels from folders, applies basic transformations, and can be used with a DataLoader for training.
Use PyTorch's Dataset class as the base.
Load images from a given directory and labels from a CSV file.
Apply a simple transformation to convert images to tensors.
Do not use any external dataset libraries like torchvision.datasets.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
PyTorch
import os
from PIL import Image
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import pandas as pd

class CustomImageDataset(Dataset):
    def __init__(self, img_dir, labels_csv, transform=None):
        self.img_dir = img_dir
        self.labels_frame = pd.read_csv(labels_csv)
        self.transform = transform

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

    def __getitem__(self, idx):
        img_name = os.path.join(self.img_dir, self.labels_frame.iloc[idx, 0])
        image = Image.open(img_name).convert('RGB')
        label = self.labels_frame.iloc[idx, 1]
        if self.transform:
            image = self.transform(image)
        return image, label

# Example usage:
if __name__ == '__main__':
    transform = transforms.ToTensor()
    dataset = CustomImageDataset(img_dir='images', labels_csv='labels.csv', transform=transform)
    dataloader = DataLoader(dataset, batch_size=4, shuffle=True)

    for images, labels in dataloader:
        print(f'Batch images shape: {images.shape}')
        print(f'Batch labels: {labels}')
        break
Created a CustomImageDataset class inheriting from torch.utils.data.Dataset.
Implemented __init__ to load image directory path and labels from CSV.
Implemented __len__ to return dataset size.
Implemented __getitem__ to load an image and its label, apply transform, and return them.
Added example usage with DataLoader to test batch loading.
Results Interpretation

Before: No data loading, no training possible.

After: Custom Dataset class loads images and labels correctly, enabling model training.

Creating a custom Dataset class in PyTorch allows you to load and preprocess your own data efficiently, which is essential for training models on custom datasets.
Bonus Experiment
Extend the Custom Dataset class to include data augmentation such as random horizontal flips and random crops.
💡 Hint
Use torchvision.transforms.Compose to combine multiple transformations including RandomHorizontalFlip and RandomResizedCrop.

Practice

(1/5)
1. What is the main purpose of creating a Custom Dataset class in PyTorch?
easy
A. To visualize data samples
B. To organize and provide access to data samples for model training
C. To perform gradient descent optimization
D. To define the neural network architecture

Solution

  1. Step 1: Understand Dataset role

    A Custom Dataset class is designed to organize data and provide easy access to samples during training.
  2. Step 2: Differentiate from other components

    Neural network architecture and optimization are handled elsewhere, not by the Dataset class.
  3. Final Answer:

    To organize and provide access to data samples for model training -> Option B
  4. Quick Check:

    Dataset class = data access [OK]
Hint: Dataset class organizes data for training access [OK]
Common Mistakes:
  • Confusing Dataset with model definition
  • Thinking Dataset handles optimization
  • Assuming Dataset visualizes data
2. Which method must be implemented in a PyTorch Custom Dataset class to return the number of samples?
easy
A. __getitem__
B. __init__
C. __len__
D. forward

Solution

  1. Step 1: Recall Dataset methods

    __len__ returns the total number of samples in the dataset.
  2. Step 2: Identify other methods' roles

    __getitem__ fetches a sample, __init__ initializes the dataset, forward is for models, not datasets.
  3. Final Answer:

    __len__ -> Option C
  4. Quick Check:

    Count samples = __len__ [OK]
Hint: Count samples with __len__ method [OK]
Common Mistakes:
  • Using __getitem__ to get length
  • Confusing __init__ with length method
  • Using forward method in Dataset
3. Given this Custom Dataset code, what will print(len(dataset)) output?
import torch
from torch.utils.data import Dataset

class MyDataset(Dataset):
    def __init__(self):
        self.data = [10, 20, 30, 40]
    def __len__(self):
        return len(self.data)
    def __getitem__(self, idx):
        return self.data[idx]

dataset = MyDataset()
medium
A. 4
B. 3
C. 40
D. Error

Solution

  1. Step 1: Check __len__ method

    __len__ returns length of self.data, which is a list of 4 elements.
  2. Step 2: Evaluate print output

    Calling len(dataset) calls __len__, so output is 4.
  3. Final Answer:

    4 -> Option A
  4. Quick Check:

    len([10,20,30,40]) = 4 [OK]
Hint: len(dataset) calls __len__ returning data length [OK]
Common Mistakes:
  • Confusing length with last element value
  • Expecting __getitem__ output instead of length
  • Assuming error without checking code
4. Identify the error in this Custom Dataset class:
from torch.utils.data import Dataset

class SampleDataset(Dataset):
    def __init__(self, data):
        self.data = data
    def __len__(self):
        return self.data
    def __getitem__(self, idx):
        return self.data[idx]

sample = SampleDataset([1,2,3])
print(len(sample))
medium
A. Missing __init__ method
B. __getitem__ returns wrong index
C. Dataset class not imported
D. __len__ returns data list instead of its length

Solution

  1. Step 1: Analyze __len__ method

    __len__ returns self.data, which is a list, not an integer length.
  2. Step 2: Understand len() requirement

    len() expects __len__ to return an integer. Returning a list causes a TypeError.
  3. Final Answer:

    __len__ returns data list instead of its length -> Option D
  4. Quick Check:

    __len__ must return int, not list [OK]
Hint: __len__ must return integer length [OK]
Common Mistakes:
  • Returning data list instead of length in __len__
  • Ignoring import statements
  • Confusing __getitem__ with __len__
5. You want to create a Custom Dataset class that returns both input features and labels from two separate lists. Which implementation correctly achieves this?
hard
A. class MyDataset(Dataset): def __init__(self, inputs, labels): self.inputs = inputs self.labels = labels def __len__(self): return len(self.inputs) def __getitem__(self, idx): return self.inputs[idx], self.labels[idx]
B. class MyDataset(Dataset): def __init__(self, inputs, labels): self.data = inputs + labels def __len__(self): return len(self.data) def __getitem__(self, idx): return self.data[idx]
C. class MyDataset(Dataset): def __init__(self, inputs, labels): self.inputs = inputs self.labels = labels def __len__(self): return len(self.labels) def __getitem__(self, idx): return self.inputs[idx]
D. class MyDataset(Dataset): def __init__(self, inputs, labels): self.inputs = inputs self.labels = labels def __len__(self): return len(self.inputs) def __getitem__(self, idx): return self.labels[idx]

Solution

  1. Step 1: Check __init__ and __len__ consistency

    The correct implementation stores inputs and labels separately and returns length of inputs in __len__, assuming matching lengths with labels.
  2. Step 2: Verify __getitem__ returns both features and labels

    The correct __getitem__ returns a tuple (self.inputs[idx], self.labels[idx]) for supervised learning.
  3. Final Answer:

    return self.inputs[idx], self.labels[idx] -> Option A
  4. Quick Check:

    Return (input, label) tuple in __getitem__ [OK]
Hint: Return (input, label) tuple in __getitem__ [OK]
Common Mistakes:
  • Combining inputs and labels into one list
  • Returning only inputs or only labels
  • Mismatched lengths in __len__
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