Create a DataLoader
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) that returns a DataLoader for the given dataset with the specified batch size (no shuffling).
Output Format
Return a DataLoader object.
Example:
dataset (6 samples), batch_size=2, shuffle=False
DataLoader with 3 batches
DataLoader automatically handles batching - 6 samples with batch_size=2 gives 3 batches
Constraints:
- Use torch.utils.data.DataLoader
- batch_size will be a positive integer
- shuffle will be a boolean
1. Background Knowledge
PyTorch Data Pipeline Fundamentals PyTorch training relies on a Dataset → DataLoader → Model pipeline. The Dataset class defines how to access individual samples via getitem(idx) and len(). The DataLoader automates batching, shuffling, and parallel loading.
Key Concepts:
- Batching: Stack N samples into tensors of shape (batch_size, *sample_shape)
- Collation: default_collate() automatically stacks tensors, lists, or dicts
- Iterators: DataLoader is iterable; next(iter(loader)) yields first batch
- No shuffling: shuffle=False preserves dataset order (important for testing)
Mathematical Perspective: For dataset size N and batch size B, DataLoader yields ⌈N/B⌉ batches. Last batch may be smaller unless drop_last=True.
2. Algorithm Approach
Core Algorithm: Wrapper pattern
Input: Dataset D, batch_size B
Output: DataLoader instance
1. Initialize DataLoader(D, batch_size=B, shuffle=False, num_workers=0)
2. Return loader
DataLoader Parameters (most relevant):
| Parameter | Purpose | Default | This Problem |
|---|---|---|---|
| batch_size | Samples per batch | 1 | Required |
| shuffle | Randomize order | False | False |
| num_workers | Parallel loading | 0 | 0 (simple) |
| drop_last | Drop incomplete batch | False | False |
Collation Flow:
[sample1, sample2,...] → default_collate() → (features_batch, labels_batch)
3. Step-by-Step Strategy
from torch.utils.data import DataLoader
def create_dataloader(dataset, batch_size):
# Step 1: Create DataLoader with exact parameters
loader = DataLoader(
dataset,
batch_size=batch_size, # Required parameter
shuffle=False # No shuffling per problem spec
)
return loader
Continue the full explanation
You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
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.