Command Palette

Search for a command to run...

Hectal
Phase 14: Working with Data: NumPy and pandas
Python · Exercise 6 of 6 Previous
Intermediate

Split data into train and test sets by hand

In machine learning you keep some rows back to test the model (Topic 14.7). Write split(X, y, test_fraction, seed) where X is a 2-D array (one example per row) and y a 1-D array with one label (the right answer) per row of X. Shuffle the row numbers with np.random.default_rng(seed).permutation(len(X)). Put the first round(len(X) * test_fraction) shuffled row numbers in the test set and the rest in the train set.

Return X_train, X_test, y_train, y_test. The same seed must always give the same split, and each row of X must stay paired with its own label. For 10 rows and test_fraction 0.3 the example prints (7, 2) (3, 2).

What Check tests

  1. The sizes are 7 train rows and 3 test rows
  2. No row is in both sets, and none is lost
  3. Each row stays with its own label
  4. The same seed gives the same split
  5. The test size is round(len(X) * test_fraction)
  6. X and y are not shuffled in place
  7. A different seed gives a different split

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.