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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With