Undersample for Class Balance
~15 mincode completion
Implement undersample(y, n_per_class) that returns a sorted integer array of selected sample indices.
Examples
- Input
- undersample([0, 0, 0, 1, 1, 1], 2)
- Output
- [0, 1, 3, 4]
3-class dataset: keep 1 from each class
- Input
- undersample([0, 1, 0, 1, 2, 2], 1)
- Output
- [0, 1, 4]
Single class with 3 samples: keep first 2
- Input
- undersample([1, 1, 1], 2)
- Output
- [0, 1]
Hints
Hint 1
picks between two values elementwise without branching.
Hint 2
Return sample indices rather than class labels.
Requirements
y: 1D integer array of class labels, shape (n,)n_per_class: Maximum number of samples to keep per classReturn Sorted 1D integer array of selected sample indices.
Constraints
Allowed library: NumPy only
Time limit: 200 ms, Memory: 64 MB
Where this shows up
~15 min
••••••••••••••••
8 employers weight this skill
3 quant funds, 2 big tech firms, 1 health and bio company, 1 AI product company, 1 defense company. Top match scores 75.
Python
import numpy as np
def undersample(y: np.ndarray, n_per_class: int) -> np.ndarray:
"""
Keep the first n_per_class sample indices for each class.
Args:
y: 1D integer array of class labels, shape (n,)
n_per_class: Maximum number of samples to keep per class
Returns:
Sorted 1D integer array of selected sample indices.
"""
# YOUR CODE HERE
pass