v9.1.1
Menu

Custom Dataset Class

mediumFREEDatasetsPyTorch DatasetsPytorch

Problem Statement

Create a custom PyTorch Dataset that wraps in-memory features and labels.

Background

PyTorch's Dataset interface is how training loops and DataLoader read samples. A map-style dataset implements three methods:

  • init: store (or prepare) the data
  • len: return the number of samples
  • getitem(idx): return the sample at position idx

Your Task

Write a class NumberDataset(features, labels) that subclasses torch.utils.data.Dataset:

  • Store features as a float32 tensor and labels as an int64 (long) tensor.
  • len(dataset) returns the number of samples.
  • dataset[i] returns the tuple (feature_tensor, label_tensor) for sample i.

Example

Input
features=[[1.0, 2.0], [3.0, 4.0]], labels=[0, 1]
Output
Dataset with 2 samples, dataset[0] returns (tensor([1., 2.]), tensor(0))
Reasoning
  • Inputs: features is a list of N=2N = 2 samples, each a vector of 2 real numbers: x0=(1.0,2.0)x_0 = (1.0, 2.0), x1=(3.0,4.0)x_1 = (3.0, 4.0). labels holds one integer class per sample: y0=0y_0 = 0, y1=1y_1 = 1. Row ii of the features pairs with entry ii of the labels.
  • Length: the dataset size is the number of samples NN (rows of features), so it is 2, not 4 (the total count of numbers).
  • Indexing: sample 00 is the pair (x0,y0)(x_0, y_0): a feature tensor holding [1., 2.] and a label tensor holding 0. Sample 11 would give (3.,4.)(3., 4.) with label 11.
  • Output types: the feature is a 1-D tensor of length 2 with 32-bit floats, which is why it prints 1. and 2.. The label is a 0-dimensional (scalar) tensor with a 64-bit integer, so it prints with no decimal point; classification losses expect integer class indices.
  • Notice that indexing drops the sample dimension: the stored features form a 2×22 \times 2 grid, but one sample is just a length-2 vector.

Constraints

  • Features and labels lists will have the same length
  • Features can be 1D or 2D lists
  • Labels are integers
  • Return tensors (not lists) from getitem

Learn this in

More from Pytorch

solution.py

Test results

Sign in to run your code against the test cases.