Bird
Raised Fist0
PyTorchml~20 mins

Dataset class (custom datasets) in PyTorch - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Custom Dataset Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a simple custom Dataset __getitem__
What is the output of this code snippet when accessing dataset[1]?
PyTorch
import torch
from torch.utils.data import Dataset

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

dataset = MyDataset()
print(dataset[1])
A40
BIndexError
C30
D20
Attempts:
2 left
💡 Hint
Remember __getitem__ returns data[idx] multiplied by 2.
❓ data_output
intermediate
2:00remaining
Length of a custom Dataset
What is the output of len(dataset) for this custom Dataset?
PyTorch
from torch.utils.data import Dataset

class SampleDataset(Dataset):
    def __init__(self):
        self.samples = list(range(7))
    def __len__(self):
        return len(self.samples)
    def __getitem__(self, idx):
        return self.samples[idx]

dataset = SampleDataset()
print(len(dataset))
A6
B7
CTypeError
D8
Attempts:
2 left
💡 Hint
Check how many elements are in samples list.
🔧 Debug
advanced
2:00remaining
Identify the error in this custom Dataset code
What error will this code raise when trying to create the dataset instance?
PyTorch
from torch.utils.data import Dataset

class BrokenDataset(Dataset):
    def __init__(self):
        self.data = [1, 2, 3]
    def __getitem__(self, idx):
        return self.data[idx]

# Missing __len__ method

dataset = BrokenDataset()
print(len(dataset))
ATypeError: object of type 'BrokenDataset' has no len()
BAttributeError: 'BrokenDataset' object has no attribute '__len__'
CNo error, dataset created successfully
DIndexError when accessing dataset[0]
Attempts:
2 left
💡 Hint
Dataset requires __len__ method to work properly.
🚀 Application
advanced
2:00remaining
Custom Dataset with transform application
Given this custom Dataset, what will be the output of dataset[0]?
PyTorch
from torch.utils.data import Dataset

def add_five(x):
    return x + 5

class TransformDataset(Dataset):
    def __init__(self, data, transform=None):
        self.data = data
        self.transform = transform
    def __len__(self):
        return len(self.data)
    def __getitem__(self, idx):
        sample = self.data[idx]
        if self.transform:
            sample = self.transform(sample)
        return sample

data = [1, 2, 3]
dataset = TransformDataset(data, transform=add_five)
print(dataset[0])
A1
B5
CTypeError
D6
Attempts:
2 left
💡 Hint
Transform adds 5 to the original data element.
🧠 Conceptual
expert
2:00remaining
Why implement a custom Dataset class in PyTorch?
Which of the following is the best reason to create a custom Dataset class in PyTorch?
ATo replace the need for DataLoader in batching data
BTo automatically parallelize model training across GPUs
CTo define how to load and access data samples and their labels efficiently
DTo speed up the training by compiling the model
Attempts:
2 left
💡 Hint
Think about what Dataset controls in PyTorch data handling.

Practice

(1/5)
1. What is the main purpose of creating a custom Dataset class in PyTorch?
easy
A. To organize and provide access to your data for training models
B. To define the neural network architecture
C. To perform data visualization
D. To optimize the training speed automatically

Solution

  1. Step 1: Understand Dataset role

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

    Neural network architecture and visualization are separate tasks, not handled by Dataset classes.
  3. Final Answer:

    To organize and provide access to your data for training models -> Option A
  4. Quick Check:

    Dataset class = data organization [OK]
Hint: Dataset class organizes data for model input [OK]
Common Mistakes:
  • Confusing Dataset with model definition
  • Thinking Dataset handles visualization
  • Assuming Dataset optimizes training speed
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. load_data

Solution

  1. Step 1: Recall Dataset methods

    __len__ returns the total number of samples in the dataset.
  2. Step 2: Differentiate from other methods

    __getitem__ fetches a sample, __init__ initializes the dataset, load_data is not a standard method.
  3. Final Answer:

    __len__ -> Option C
  4. Quick Check:

    Count samples = __len__ [OK]
Hint: Use __len__ to get dataset size [OK]
Common Mistakes:
  • Using __getitem__ to get length
  • Confusing __init__ with length method
  • Assuming load_data is required
3. What will be the output of this code snippet?
import torch
from torch.utils.data import Dataset

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

dataset = MyDataset()
print(len(dataset))
print(dataset[1])
medium
A. 3 and 40
B. 3 and 20
C. Error due to missing DataLoader
D. 3 and 30

Solution

  1. Step 1: Calculate length of dataset

    len(dataset) calls __len__, which returns length of self.data = 3.
  2. Step 2: Calculate dataset[1]

    dataset[1] calls __getitem__ with idx=1, returns self.data[1]*2 = 20*2 = 40.
  3. Final Answer:

    3 and 40 -> Option A
  4. Quick Check:

    Length=3, item*2=40 [OK]
Hint: Remember __getitem__ transforms data on access [OK]
Common Mistakes:
  • Confusing index values
  • Expecting error without DataLoader
  • Forgetting the multiplication by 2
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]
medium
A. __getitem__ should return the index, not data element
B. __len__ should return an integer, not the data list
C. Missing __init__ method
D. Dataset class should inherit from torch.nn.Module

Solution

  1. Step 1: Check __len__ method

    __len__ returns self.data, which is a list, but it must return an integer length.
  2. Step 2: Verify other methods

    __getitem__ correctly returns data element; __init__ is present; Dataset inheritance is correct.
  3. Final Answer:

    __len__ should return an integer, not the data list -> Option B
  4. Quick Check:

    __len__ must return length integer [OK]
Hint: __len__ must return integer length [OK]
Common Mistakes:
  • Returning list instead of length in __len__
  • Confusing Dataset with nn.Module
  • Omitting __init__ method
5. You want to create a custom Dataset that loads images and their labels from a folder. Which of these is the best approach to implement the __getitem__ method?
hard
A. Load all images in __init__ and return preloaded images in __getitem__
B. Return the file path as a string without loading the image
C. Only return labels in __getitem__, ignore images
D. Load the image file from disk, apply transformations, and return the image and label

Solution

  1. Step 1: Understand __getitem__ role

    __getitem__ should load and return the actual data sample and label when requested.
  2. Step 2: Evaluate options

    Loading image on demand with transformations is efficient and standard. Returning file path or only labels is incomplete. Loading all images in __init__ can use too much memory.
  3. Final Answer:

    Load the image file from disk, apply transformations, and return the image and label -> Option D
  4. Quick Check:

    __getitem__ loads and returns data [OK]
Hint: Load and transform data inside __getitem__ [OK]
Common Mistakes:
  • Loading all data in __init__ causing memory issues
  • Returning file paths instead of data
  • Ignoring images and returning only labels
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