v9.1.1
Menu

Create a DataLoader

easyPRODatasetsPyTorch DatasetsPytorch

Problem Statement

Create a DataLoader to batch a dataset.

Background

DataLoader wraps a Dataset and provides automatic batching, shuffling, and parallel loading — the standard way to feed data into a training loop.

Your Task

Write a function create_dataloader(dataset, batch_size=2, shuffle=False) that returns a DataLoader for the given dataset with the specified batch size, shuffling only when shuffle is true (default: no shuffling).

Output Format

Return a DataLoader object.

Example

Input
dataset (6 samples), batch_size=2, shuffle=False
Output
DataLoader with 3 batches
Reasoning
  • Input: dataset holds N=6N = 6 samples, each a (feature vector, label) pair, e.g. features [1,2],[3,4],…,[11,12][1, 2], [3, 4], \ldots, [11, 12] with labels 0,1,0,1,0,10, 1, 0, 1, 0, 1. batch_size =2= 2 is how many samples get grouped together, and shuffle is off, so samples keep their original order.
  • Math: the number of batches is ⌈N/B⌉=⌈6/2⌉=3\lceil N / B \rceil = \lceil 6 / 2 \rceil = 3. Batch 1 is samples 1–2, batch 2 is samples 3–4, batch 3 is samples 5–6.
  • What one batch looks like: the samples are stacked along a new leading axis, so batch 1 gives features [1234]\begin{bmatrix}1 & 2\\ 3 & 4\end{bmatrix} (a 2×22 \times 2 array: batch size ×\times feature count) and labels [0,1][0, 1] (length 2).
  • Output: an iterable object, not a list of numbers; its length is the batch count, 3.
  • Notice that the last batch can be smaller: with N=10N = 10 and B=3B = 3 you get ⌈10/3⌉=4\lceil 10/3 \rceil = 4 batches of sizes 3,3,3,13, 3, 3, 1.

Constraints

  • Use torch.utils.data.DataLoader
  • batch_size will be a positive integer
  • shuffle will be a boolean

Learn this in

More from Pytorch

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.