PyTorch Dataset

A dataset is a Python object that can retrieve an data item by index, and can also return the size of the dataset. The following is sample code that inplements a dataset, with the functionality of each function missing.

class Dataset(obj): def __getitem__(self, index): pass def __len__(self): pass pass

Sample Code

The following code generates a random dataset.

class RandomClassificationDataset(Dataset): def __init__(self, num_samples, input_size, num_classes): # Generate dummy data (X) and labels (y) self.X = torch.randn(num_samples, input_size) self.y = torch.randint(0, num_classes, (num_samples,)) def __len__(self): # Must return the total number of samples return len(self.X) def __getitem__(self, idx): # Must return a single sample (features, label) at the given index return self.X[idx], self.y[idx]