Iterate Through DataLoader
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
7 samples, batch_size=3
{"num_batches": 3, "first_batch_size": 3, "last_batch_size": 1, "total_samples": 7}- Input: a loader over a dataset of samples (each a feature row plus a label), served in order with batch size . A batch's size is the number of samples in it.
- Batching: samples are taken at a time until the dataset runs out, so there are batches. The first two are full ( and ); the third gets the leftover sample, i.e. .
- Statistics:
num_batchescounts the batches (),first_batch_sizeis the size of batch 1 (),last_batch_sizeis the size of the final batch (), andtotal_samplesadds all sizes: . - Notice:
total_samplesalways recovers , whilelast_batch_sizeequals only when divides (6 samples with gives ). If , one batch holds everything, so first and last are the same batch (5 samples with gives and ).
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