v9.1.1
Menu

Create TensorDataset

easyFREEDatasetsPyTorch DatasetsPytorch

Problem Statement

Create a TensorDataset from feature and label tensors.

Background

TensorDataset wraps tensors so they can be used with PyTorch's data loading utilities, pairing features with their corresponding labels automatically.

Your Task

Write a function create_tensor_dataset(features, labels) that wraps the two tensors in a TensorDataset and returns it.

Output Format

Return the TensorDataset. The tests check len(dataset), the number of samples it contains.

Example

Input
features=torch.tensor([[1.0, 2.0], [3.0, 4.0]]), labels=torch.tensor([0, 1])
Output
TensorDataset with 2 samples
Reasoning
  • Inputs: features is a 2×22 \times 2 float tensor, one row per sample and one column per feature, so sample 0 is (1.0,2.0)(1.0, 2.0) and sample 1 is (3.0,4.0)(3.0, 4.0). labels is a length-2 integer tensor holding one class per sample: 00 and 11.
  • Pairing: both tensors share the same first dimension, N=2N = 2. The dataset lines them up along that dimension, so index ii means "row ii of features together with entry ii of labels".
  • Worked example: index 00 gives the pair ((1.0,2.0), 0)\big((1.0, 2.0),\ 0\big) and index 11 gives ((3.0,4.0), 1)\big((3.0, 4.0),\ 1\big). No values are copied, changed or reordered.
  • Output: the length of the dataset is the number of samples NN, not the total number of feature values (2×2=42 \times 2 = 4) and not the number of features per sample. That is why the output reads TensorDataset with 2 samples.
  • Notice: a test with 10 samples of 5 features each has length 1010; the feature width never affects the count.

Constraints

  • Use torch.utils.data.TensorDataset
  • Both tensors will have the same first dimension
  • Features is a 2D tensor, labels is a 1D tensor

Learn this in

More from Pytorch

solution.py

Test results

Sign in to run your code against the test cases.