liveBook · Manning

__getitem__

As explained in Deep Learning with PyTorch, Second Edition

A Python special method that retrieves an item by index or key, used here by Dataset to return a sample and label.

__getitem__ is the Python special method that lets a PyTorch Dataset return one item when accessed with subscription syntax such as dataset[index]. A returned item may contain a sample and label, or any other data point. section 7.1.2

A Dataset implementation uses __getitem__ to:

  • Accept an index, typically an integer from 0 through N−1 when __len__ returns N. section 12.5
  • Retrieve or construct the corresponding sample and format it into the data types and dimensions required downstream. section 12.5
  • Return a problem-specific value, such as an image-label pair or a four-item training tuple. section 7.1.2 section 12.5

Indexing CIFAR-10

img, label = cifar10[99] retrieves a PIL RGB image and integer label 1; interpreting that label through class_names gives “automobile.” section 7.1.2

Building a custom sample

A custom implementation can select candidateInfo_list[ndx], load a candidate, convert it to a float tensor with an added dimension, create a label tensor, and return those values with identifiers and coordinates. section 12.5

Figure 7.2 Concept of a PyTorch Dataset object. It doesn’t necessarily hold the data, but it provides uniform access to it through __len__ and __getitem__.
figure

Shows Dataset as a uniform access interface built around __len__ and __getitem__, without requiring the object itself to hold all data. section 7.1.2

How Deep Learning with PyTorch, Second Edition covers it

How deep it goes
Defines the index contract and demonstrates sample construction, tensor conversion, dimensions, and multi-value returns without descending into method internals.
Examples
Uses CIFAR-10 image access and a LunaDataset tuple containing tensors, a series identifier, and coordinates.
What it assumes
Assumes basic Python subscription syntax and introduces the Dataset method requirements through concrete image and custom-data examples.
What you can do after
Apply it via PyTorch Dataset subclassing to retrieve and format indexed samples for training or validation.
How it connects
Connects Dataset, __len__, Python indexing, samples, labels, tensors, and training or validation data.

Also explained in

Compare how 2 books explain __getitem__ →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with PyTorch, Second Edition. The section links point to the parts of the book it draws on.