Split features and labels while approximating the same class proportions in train and test. For each class with nc samples, compute:
nctest=round(nct)Here, t is test_size. When a class has more than one sample, cap its test count at nc−1 so at least one remains in training. Create one generator with np.random.default_rng(seed) and reuse it for every class, visiting the classes in ascending label order. Shuffle the indices of each class and send the first nctest shuffled indices to the test set and the remaining ones to the training set. Combine the selected indices, sort each final index set, and return X_train, X_test, y_train, and y_test as NumPy arrays in a dictionary.
Input: X = [0, 1, 2, 3, 4, 5], y = [0, 0, 0, 1, 1, 1], test_size = 0.33, seed = 42
Output: {"X_train": [0, 1, 4, 5], "X_test": [2, 3], "y_train": [0, 0, 1, 1], "y_test": [0, 1]}
Explanation: One seeded sample from each class enters the test split.
Input: X = [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0], [10, 0]], y = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], test_size = 0.3, seed = 42
Output: {"X_train": [[1, 0], [2, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]], "X_test": [[3, 0], [4, 0], [10, 0]], "y_train": [0, 0, 0, 0, 0, 1, 1], "y_test": [0, 0, 1]}
Use np.flatnonzero(y == label) and rng.permutation for each class.
Accumulate class indices, then apply np.sort before indexing X and y.
Accepts: array
Accepts: array
Accepts: number
Accepts: number
Split features and labels while approximating the same class proportions in train and test. For each class with nc samples, compute:
nctest=round(nct)Here, t is test_size. When a class has more than one sample, cap its test count at nc−1 so at least one remains in training. Create one generator with np.random.default_rng(seed) and reuse it for every class, visiting the classes in ascending label order. Shuffle the indices of each class and send the first nctest shuffled indices to the test set and the remaining ones to the training set. Combine the selected indices, sort each final index set, and return X_train, X_test, y_train, and y_test as NumPy arrays in a dictionary.
Input: X = [0, 1, 2, 3, 4, 5], y = [0, 0, 0, 1, 1, 1], test_size = 0.33, seed = 42
Output: {"X_train": [0, 1, 4, 5], "X_test": [2, 3], "y_train": [0, 0, 1, 1], "y_test": [0, 1]}
Explanation: One seeded sample from each class enters the test split.
Input: X = [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0], [10, 0]], y = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], test_size = 0.3, seed = 42
Output: {"X_train": [[1, 0], [2, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]], "X_test": [[3, 0], [4, 0], [10, 0]], "y_train": [0, 0, 0, 0, 0, 1, 1], "y_test": [0, 0, 1]}
Use np.flatnonzero(y == label) and rng.permutation for each class.
Accumulate class indices, then apply np.sort before indexing X and y.
Accepts: array
Accepts: array
Accepts: number
Accepts: number