InterviewPrepKit

Home / Coding / Machine Learning Coding / Numerical & Data / Train/Test Split

Train/Test Split

easy 00:00
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).

  • X has shape (n, d) and y has shape (n,); row i of X corresponds to y[i].
  • Build an index array 0..n-1 and shuffle it with a numpy Generator seeded by seed (np.random.default_rng(seed)).
  • The test set is the first int(n * test_size) shuffled indices; the train set is the remainder.
  • Index X and y with 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 seed must always produce the same split.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug