MediumData Processing

Batch Shuffling & Mini-Batch Generator

Data Processing

Medium

Problem

Shuffle matching feature and label arrays once, then yield consecutive mini-batches. Use np.random.default_rng(seed) to shuffle one index array and apply it to both inputs. Each yield must be a tuple (X_batch, y_batch) containing NumPy arrays. If drop_last is true, omit a final batch smaller than batch_size.

Theory

In machine learning, training on entire datasets at once is often impractical due to memory constraints. Mini-batch training processes data in small, manageable chunks called batches. A batch generator creates these batches on-the-fly, enabling efficient training of large-scale models.


Why Batch Training Matters

When training neural networks, the choice of batch size affects three critical factors:

\nabla_\theta L_{batch} \approx \nabla_\theta L_{full}


The Mathematics of Batching

Given a dataset of N samples and batch size B:

The drop_last parameter determines whether to discard the final incomplete batch:


Shuffling and Randomization

Shuffling data between epochs prevents the model from learning order-dependent patterns:


Handling Paired Data

When features X and labels y must stay aligned, shuffling must maintain correspondence:


Epoch vs Iteration Terminology


Stratified Batching

For imbalanced classification, random batching may produce batches with skewed class distributions:


Generator Pattern Benefits

A generator produces batches lazily rather than creating all batches upfront:


Practical Considerations


Where Batch Generators Show Up

Examples

Example 1

Input
X = [0, 1, 2, 3, 4, 5, 6], y = [0, 1, 2, 3, 4, 5, 6], batch_size = 3, seed = 42, drop_last = False
Output
[[[3, 2, 6], [3, 2, 6]], [[4, 1, 5], [4, 1, 5]], [[0], [0]]]
Explanation
One seeded permutation is sliced into batches of three, with the final single sample retained.

Example 2

Input
X = [0, 1, 2, 3, 4, 5, 6], y = [0, 1, 2, 3, 4, 5, 6], batch_size = 3, seed = 42, drop_last = True
Output
[[[3, 2, 6], [3, 2, 6]], [[4, 1, 5], [4, 1, 5]]]

Hints

  1. Shuffle np.arange(len(X)) with np.random.default_rng(seed).
  2. Slice the shuffled indices inside range(0, len(indices), batch_size).

Requirements

Constraints

Starter Code

import numpy as np

def batch_generator(X: list, y: list, batch_size: int, seed: int = 42, drop_last: bool = False):
    """
    Returns a generator of (X_batch, y_batch) tuples.
    """
    # Write code here
    pass

Test Cases

CaseMatches
drop last=False (keeps incomplete)public
drop last=True (drops incomplete)public