Randomly shuffle a dataset and yield mini-batches (X_batch, y_batch) of size batch_size.
Your function should create a Python generator that shuffles the input data once, then yields consecutive chunks (batches) of the specified size. Each yielded batch contains corresponding slices of features (X) and labels (y) from the shuffled data.
X: array-like, shape (N, D) or (N,) - Featuresy: array-like, shape (N,) - Labelsbatch_size: int > 0 - Size of each batchrng: optional np.random.Generator - For deterministic shufflingdrop_last: bool - If True, discard final short batchInput: X=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], batch_size=3, drop_last=False
Output: (X=[3,2,6], y=[3,2,6]), (X=[4,1,5], y=[4,1,5]), (X=[0], y=[0])
7 items, batch_size=3 → 3 batches. Last batch has only 1 item but is kept because drop_last=False.
Input: X=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], batch_size=3, drop_last=True
Output: (X=[3,2,6], y=[3,2,6]), (X=[4,1,5], y=[4,1,5])
Same data but drop_last=True → incomplete last batch (size 1 < 3) is dropped. Only 2 full batches yielded.
Create indices array, shuffle it, then slice X and y using shuffled indices.
Use yield to create a generator. Loop with range().
Use rng.shuffle() if rng provided, else np.random.shuffle().
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number
Accepts: any
Randomly shuffle a dataset and yield mini-batches (X_batch, y_batch) of size batch_size.
Your function should create a Python generator that shuffles the input data once, then yields consecutive chunks (batches) of the specified size. Each yielded batch contains corresponding slices of features (X) and labels (y) from the shuffled data.
X: array-like, shape (N, D) or (N,) - Featuresy: array-like, shape (N,) - Labelsbatch_size: int > 0 - Size of each batchrng: optional np.random.Generator - For deterministic shufflingdrop_last: bool - If True, discard final short batchInput: X=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], batch_size=3, drop_last=False
Output: (X=[3,2,6], y=[3,2,6]), (X=[4,1,5], y=[4,1,5]), (X=[0], y=[0])
7 items, batch_size=3 → 3 batches. Last batch has only 1 item but is kept because drop_last=False.
Input: X=[0,1,2,3,4,5,6], y=[0,1,2,3,4,5,6], batch_size=3, drop_last=True
Output: (X=[3,2,6], y=[3,2,6]), (X=[4,1,5], y=[4,1,5])
Same data but drop_last=True → incomplete last batch (size 1 < 3) is dropped. Only 2 full batches yielded.
Create indices array, shuffle it, then slice X and y using shuffled indices.
Use yield to create a generator. Loop with range().
Use rng.shuffle() if rng provided, else np.random.shuffle().
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number
Accepts: any