Custom Dataset Class
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
features=[[1.0, 2.0], [3.0, 4.0]], labels=[0, 1]
Dataset with 2 samples, dataset[0] returns (tensor([1., 2.]), tensor(0))
- Inputs:
featuresis a list of samples, each a vector of 2 real numbers: , .labelsholds one integer class per sample: , . Row of the features pairs with entry of the labels. - Length: the dataset size is the number of samples (rows of features), so it is
2, not 4 (the total count of numbers). - Indexing: sample is the pair : a feature tensor holding
[1., 2.]and a label tensor holding0. Sample would give with label . - Output types: the feature is a 1-D tensor of length 2 with 32-bit floats, which is why it prints
1.and2.. 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 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