Sobes.tech
Middle

What methods need to be implemented when inheriting from the Dataset class in PyTorch?

sobes.tech AI

Answer from AI

When inheriting from the Dataset class in PyTorch, you need to implement at least two methods:

  • __len__(self) — returns the number of elements in the dataset.
  • __getitem__(self, idx) — returns the element at index idx.

Example:

from torch.utils.data import Dataset

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]

These methods allow DataLoader and other PyTorch components to work correctly with your dataset.