These two methods help your data class tell PyTorch how many items it has and how to get each item. This makes it easy to use your data in training.
When you create a custom dataset to feed data into a PyTorch model.
When you want to load images or text samples one by one during training.
When your data is not in a ready-made format and you need to control how it is accessed.
When you want to use PyTorch's DataLoader to automatically handle batching and shuffling.
Syntax
PyTorch
class YourDataset(torch.utils.data.Dataset):
def __len__(self):
# return number of itemsreturn number_of_items
def __getitem__(self, index):
# return one data item at position indexreturn data_item
__len__ tells how many items are in your dataset.
__getitem__ returns one item when given an index number.
This code creates a dataset of numbers 0 to 9. The __getitem__ returns double the number. The DataLoader loads data in batches of 3 and prints each batch.
PyTorch
import torch
from torch.utils.data import Dataset, DataLoader
class SimpleDataset(Dataset):
def __init__(self):
self.data = [i for i inrange(10)] # numbers 0 to 9def __len__(self):
returnlen(self.data)
def __getitem__(self, idx):
return self.data[idx] * 2# return double the number# Create dataset and dataloader
dataset = SimpleDataset()
dataloader = DataLoader(dataset, batch_size=3, shuffle=False)
for batch in dataloader:
print(batch)
OutputSuccess
Important Notes
Always make sure __len__ matches the actual number of items your dataset can provide.
__getitem__ should handle any index from 0 to len(dataset)-1.
These methods let PyTorch's DataLoader work smoothly for batching and shuffling.
Summary
__len__ tells how many items are in your dataset.
__getitem__ returns one item by index.
Together, they let PyTorch load your data easily for training.
Practice
(1/5)
1. What does the __len__ method do in a PyTorch dataset class?
easy
A. It saves the dataset to disk.
B. It returns one data item by index.
C. It returns the total number of items in the dataset.
D. It trains the model on the dataset.
Solution
Step 1: Understand the role of __len__ in datasets
The __len__ method tells PyTorch how many items are in the dataset so it knows the dataset size.
Step 2: Differentiate from __getitem__
Unlike __getitem__ which returns one item, __len__ returns the total count of items.
Final Answer:
It returns the total number of items in the dataset. -> Option C
Quick Check:
__len__ = total items [OK]
Hint: Remember: length means total count, not single item [OK]
Common Mistakes:
Confusing __len__ with __getitem__
Thinking __len__ returns data samples
Assuming __len__ trains the model
2. Which of the following is the correct way to define the __getitem__ method in a PyTorch dataset class?
easy
A. def __getitem__(self, index, batch): return self.data[index:batch]
B. def __getitem__(self, index): return self.data[index]
C. def __getitem__(self): return self.data
D. def __getitem__(index): return self.data[index]
Solution
Step 1: Check method signature requirements
The __getitem__ method must accept self and an index parameter to return one item.
Step 2: Validate return statement
Returning self.data[index] correctly fetches the item at the given index.
Final Answer:
def __getitem__(self, index): return self.data[index] -> Option B
Quick Check:
__getitem__ needs self and index [OK]
Hint: Always include self and index parameters in __getitem__ [OK]
Common Mistakes:
Missing self parameter
Adding extra parameters not supported
Returning whole data instead of one item
3. Given this dataset class, what will print(len(dataset)) output?