Does pytorch Dataset.__getitem__ have to return a dict?

Viewed 2707

EDIT: This is not about the general __getitem__ method but the usage of __getitem__ in the Pytorch Dataset-subclass, as @dataista correctly states.

I'm trying to implement the usage of Pytorchs Dataset-class. The guide e.g here is really good, but I struggle to figure out Pytorch requirements for the return value of __getitem__. In the Pytorch documentation I cannot find anything about what it should return; is it any object which is iterable with size 2 e.g [sample,target], (sample,target)? In some guides they return a dict, but they do not specify if it has to be a dict which is returned.

1 Answers

PyTorch has no requirements on the return value of a DataSet's __getitem__ method. It can be anything, but you will commonly encounter a tensor, a tuple of tensors, a dictionary (e.g. {'features':..., 'label':...}) etc.

It is usual in 2d data to return a single tensor whose final column are the target values, but equally you may see tuples/dicts of the features and targets explicitly separated.

Note there is no requirement that you return two values - in many unsupervised contexts (e.g. autoencoders) there is only a set of features, with no distinct target.

Related