Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does next() and iter() do in PyTorch's DataLoader()

I have the following code:

import torch
import numpy as np
import pandas as pd
from torch.utils.data import TensorDataset, DataLoader

# Load dataset
df = pd.read_csv(r'../iris.csv')

# Extract features and target
data = df.drop('target',axis=1).values
labels = df['target'].values

# Create tensor dataset
iris = TensorDataset(torch.FloatTensor(data),torch.LongTensor(labels))

# Create random batches
iris_loader = DataLoader(iris, batch_size=105, shuffle=True)

next(iter(iris_loader))

What does next() and iter() do in the above code? I have went through PyTorch's documentation and still can quite understand what is next() and iter() doing here. Can anyone help in explaining this? Many thanks in advance.

like image 481
Leockl Avatar asked Jun 24 '20 07:06

Leockl


People also ask

What does ITER do in PyTorch?

An iterator is an object representing a stream of data. You can create an iterator object by applying the iter() built-in function to an iterable. With the stream of data, we can use Python built-in next() function to get the next data element in the stream of data.

What is next ITER in Python?

The next() function returns the next item in an iterator. You can add a default return value, to return if the iterable has reached to its end.

What does ITER do in Python?

python iter() method returns the iterator object, it is used to convert an iterable to the iterator. Parameters : obj : Object which has to be converted to iterable ( usually an iterator ). sentinel : value used to represent end of sequence.

What does DataLoader do in PyTorch?

Data loader. Combines a dataset and a sampler, and provides an iterable over the given dataset. The DataLoader supports both map-style and iterable-style datasets with single- or multi-process loading, customizing loading order and optional automatic batching (collation) and memory pinning.


1 Answers

These are built-in functions of python, they are used for working with iterables.

Basically iter() calls the __iter__() method on the iris_loader which returns an iterator. next() then calls the __next__() method on that iterator to get the first iteration. Running next() again will get the second item of the iterator, etc.

This logic often happens 'behind the scenes', for example when running a for loop. It calls the __iter__() method on the iterable, and then calls __next__() on the returned iterator until it reaches the end of the iterator. It then raises a stopIteration and the loop stops.

Please see the documentation for further details and some nuances: https://docs.python.org/3/library/functions.html#iter

like image 127
ScootCork Avatar answered Oct 15 '22 06:10

ScootCork