Solving tips
- Split by shuffling indices, not the data itself — index once at the end so X and y stay aligned.
- Seed a numpy Generator with np.random.default_rng(seed) so the shuffle is reproducible.
- Compute the test count as int(n * test_size); the first slice of shuffled indices is test, the rest is train.
Implement a train/test split from scratch with NumPy, the way sklearn.model_selection.train_test_split does but without calling it. Interviewers use this to check that you can shuffle reproducibly and keep features and labels aligned.
Task
Complete train_test_split(X, y, test_size=0.2, seed=0) so it returns (X_train, X_test, y_train, y_test).
Xhas shape(n, d)andyhas shape(n,); rowiofXcorresponds toy[i].- Build an index array
0..n-1and shuffle it with a numpy Generator seeded byseed(np.random.default_rng(seed)). - The test set is the first
int(n * test_size)shuffled indices; the train set is the remainder. - Index
Xandywith those index arrays so each pair stays aligned.
Do not call sklearn or any built-in split helper.
Example
X = np.arange(10).reshape(5, 2) # rows 0..4
y = np.array([0, 1, 2, 3, 4])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, seed=0)
# default_rng(0) shuffles [0,1,2,3,4] -> [2,4,3,0,1]
# int(5 * 0.4) = 2 test rows -> indices [2, 4]; train indices -> [3, 0, 1]
y_test # -> array([2, 4])
y_train # -> array([3, 0, 1])
X_test # -> array([[4, 5],
# [8, 9]])
Constraints
1 <= n <= 10^6; use vectorized NumPy indexing, not a Python loop.0 <= test_size <= 1.- The same
seedmust always produce the same split.