v9.1.1
Menu

Iterate Through DataLoader

mediumPRODatasetsPyTorch DatasetsPytorch

Problem Statement

Write a function that iterates through a DataLoader and collects batch statistics. This simulates the core loop used during model training.

Background

During training, you iterate through the DataLoader to process data in batches. Each iteration yields one batch, and the last batch may be smaller if the dataset size isn't evenly divisible by batch size.

Your Task

Write a function get_batch_stats(dataloader) that iterates through all batches and returns statistics about them.

Output Format

Return a dictionary with keys: "num_batches" (int), "first_batch_size" (int), "last_batch_size" (int), "total_samples" (int).

Example

Input
7 samples, batch_size=3
Output
{"num_batches": 3, "first_batch_size": 3, "last_batch_size": 1, "total_samples": 7}
Reasoning
  • Input: a loader over a dataset of N=7N = 7 samples (each a feature row plus a label), served in order with batch size B=3B = 3. A batch's size is the number of samples in it.
  • Batching: samples are taken BB at a time until the dataset runs out, so there are ⌈N/B⌉=⌈7/3⌉=3\lceil N/B \rceil = \lceil 7/3 \rceil = 3 batches. The first two are full (33 and 33); the third gets the leftover 7−2⋅3=17 - 2 \cdot 3 = 1 sample, i.e. 7 mod 3=17 \bmod 3 = 1.
  • Statistics: num_batches counts the batches (33), first_batch_size is the size of batch 1 (33), last_batch_size is the size of the final batch (11), and total_samples adds all sizes: 3+3+1=73 + 3 + 1 = 7.
  • Notice: total_samples always recovers NN, while last_batch_size equals BB only when BB divides NN (6 samples with B=2B = 2 gives 2,2,22, 2, 2). If B>NB > N, one batch holds everything, so first and last are the same batch (5 samples with B=10B = 10 gives 55 and 55).

Constraints

  • DataLoader will have at least one batch
  • Features and labels are the first two elements returned
  • Last batch may be smaller than batch_size

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.