We use custom Dataset classes to organize and load our own data easily for training machine learning models.
Dataset class (custom datasets) in PyTorch
from torch.utils.data import Dataset class CustomDataset(Dataset): def __init__(self, data, labels, transform=None): self.data = data self.labels = labels self.transform = transform def __len__(self): return len(self.data) def __getitem__(self, idx): sample = self.data[idx] label = self.labels[idx] if self.transform: sample = self.transform(sample) return sample, label
The __init__ method sets up your data and any transforms.
The __len__ method returns how many samples you have.
The __getitem__ method returns one sample and label by index.
class MyDataset(Dataset): def __init__(self, data): self.data = data def __len__(self): return len(self.data) def __getitem__(self, idx): return self.data[idx]
from torchvision.io import read_image class ImageDataset(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 = read_image(self.image_paths[idx]) label = self.labels[idx] if self.transform: image = self.transform(image) return image, label
This program creates a simple dataset with features and labels, then loads it in batches of 2 using DataLoader. It prints each batch's data and labels.
import torch from torch.utils.data import Dataset, DataLoader class SimpleDataset(Dataset): def __init__(self, data, labels): self.data = data self.labels = labels def __len__(self): return len(self.data) def __getitem__(self, idx): return self.data[idx], self.labels[idx] # Sample data features = torch.tensor([[1, 2], [3, 4], [5, 6], [7, 8]]) labels = torch.tensor([0, 1, 0, 1]) # Create dataset dataset = SimpleDataset(features, labels) # Create DataLoader to load data in batches loader = DataLoader(dataset, batch_size=2, shuffle=False) for batch_idx, (data, target) in enumerate(loader): print(f"Batch {batch_idx+1} data:", data) print(f"Batch {batch_idx+1} labels:", target)
Always return data and label as a tuple in __getitem__.
Use transforms to preprocess data inside the dataset.
DataLoader helps to load data in batches and shuffle if needed.
Custom Dataset classes help organize your data for PyTorch models.
Implement __init__, __len__, and __getitem__ methods.
Use DataLoader to load data in batches during training.
Practice
Solution
Step 1: Understand Dataset role
A custom Dataset class is designed to organize data and provide easy access to samples and labels.Step 2: Differentiate from other components
Neural network architecture and visualization are separate tasks, not handled by Dataset classes.Final Answer:
To organize and provide access to your data for training models -> Option AQuick Check:
Dataset class = data organization [OK]
- Confusing Dataset with model definition
- Thinking Dataset handles visualization
- Assuming Dataset optimizes training speed
Solution
Step 1: Recall Dataset methods
__len__ returns the total number of samples in the dataset.Step 2: Differentiate from other methods
__getitem__ fetches a sample, __init__ initializes the dataset, load_data is not a standard method.Final Answer:
__len__ -> Option CQuick Check:
Count samples = __len__ [OK]
- Using __getitem__ to get length
- Confusing __init__ with length method
- Assuming load_data is required
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])
Solution
Step 1: Calculate length of dataset
len(dataset) calls __len__, which returns length of self.data = 3.Step 2: Calculate dataset[1]
dataset[1] calls __getitem__ with idx=1, returns self.data[1]*2 = 20*2 = 40.Final Answer:
3 and 40 -> Option AQuick Check:
Length=3, item*2=40 [OK]
- Confusing index values
- Expecting error without DataLoader
- Forgetting the multiplication by 2
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]
Solution
Step 1: Check __len__ method
__len__ returns self.data, which is a list, but it must return an integer length.Step 2: Verify other methods
__getitem__ correctly returns data element; __init__ is present; Dataset inheritance is correct.Final Answer:
__len__ should return an integer, not the data list -> Option BQuick Check:
__len__ must return length integer [OK]
- Returning list instead of length in __len__
- Confusing Dataset with nn.Module
- Omitting __init__ method
__getitem__ method?Solution
Step 1: Understand __getitem__ role
__getitem__ should load and return the actual data sample and label when requested.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.Final Answer:
Load the image file from disk, apply transformations, and return the image and label -> Option DQuick Check:
__getitem__ loads and returns data [OK]
- Loading all data in __init__ causing memory issues
- Returning file paths instead of data
- Ignoring images and returning only labels
Ready to prove it?
Pass the test and this pattern moves unknown
