liveBook · Manning

__len__

As explained in Deep Learning with PyTorch, Second Edition

A Python special method that returns an object's length for the len() built-in, used here by Dataset to report item count.

__len__ is the Python special method that lets len() report an object's length. In a PyTorch Dataset, it returns the number of available items. section 7.1.2

A Dataset implementation uses __len__ alongside __getitem__ to provide uniform indexed access:

  • Return one constant dataset length; some PyTorch use cases cache this value. section 12.5
  • Make __getitem__ return a valid item for every index from 0 through N–1 when __len__ returns N. section 12.5
  • Base the result on the collection of samples, such as the length of candidateInfo_list. section 12.5

Counting dataset items

For CIFAR-10, calling len(cifar10) returns 50000. In a custom dataset, def __len__(self): return len(self.candidateInfo_list) reports the number of candidate samples. section 7.1.2 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

A diagram showing how __len__ and __getitem__ provide uniform access to a PyTorch Dataset, whether or not it stores the data directly. section 7.1.2

How Deep Learning with PyTorch, Second Edition covers it

How deep it goes
Defines the required return value and valid indexing range, but does not descend into caching behavior or sampling constraints.
Examples
Demonstrates CIFAR-10 with len(cifar10) and a custom dataset using len(candidateInfo_list).
What it assumes
Assumes basic Python objects and indexing while teaching the Dataset method requirements from the implementation context.
What you can do after
Build a PyTorch Dataset whose length agrees with the indices accepted by __getitem__.
How it connects
Connects Dataset, __getitem__, len(), indexed access, samples, labels, and class imbalance.

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.