22.02.2024 Views

Daniel Voigt Godoy - Deep Learning with PyTorch Step-by-Step A Beginner’s Guide-leanpub

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Notebook Cell 2.3 - Building a data loader for our training data

train_loader = DataLoader(

dataset=train_data,

batch_size=16,

shuffle=True,

)

To retrieve a mini-batch, one can simply run the command below—it will return a

list containing two tensors, one for the features, another one for the labels:

next(iter(train_loader))

Output

[tensor([[0.1196],

[0.1395],

...

[0.8155],

[0.5979]]), tensor([[1.3214],

[1.3051],

...

[2.6606],

[2.0407]])]

"Why not use a list instead?"

If you call list(train_loader), you’ll get, as a result, a list of five elements; that is,

all five mini-batches. Then you could take the first element of that list to obtain a

single mini-batch as in the example above. It would defeat the purpose of using the

iterable provided by the DataLoader; that is, to iterate over the elements (minibatches,

in that case) one at a time.

To learn more about it, check RealPython’s material on iterables [57] and iterators [58] .

138 | Chapter 2: Rethinking the Training Loop

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!