Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
Splitting Train and Test
A model's score on the data it was trained on tells you nothing useful. Any model complex enough can memorise its training set. The only honest measure is performance on data it has never seen.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)Four things come back, in that order. Getting them out of order is a classic and produces a model that is confidently wrong.
test_size=0.2 holds back 20 percent. random_state=42 fixes the shuffle so the split is the same every run: without it, your score changes on every execution and you cannot tell an improvement from noise.
For classification, add stratify=y so each class appears in the same proportion in both halves. On imbalanced data, a random split can put nearly all of a rare class on one side.
Your task:
Write split_sizes(X, y, test_size) that splits the data and returns [n_train, n_test], the number of rows in each half.
Use random_state=0 so the result is the same every time.
Example Tests
Holding back 20 percent of 10 rows leaves 8 for training
Input: {"X":[[1],[2],[3],[4],[5],[6],[7],[8],[9],[10]],"y":[0,1,0,1,0,1,0,1,0,1],"test_size":0.2}
Expected: [8,2]
Holding back half of 10 rows splits it evenly
Input: {"X":[[1],[2],[3],[4],[5],[6],[7],[8],[9],[10]],"y":[0,1,0,1,0,1,0,1,0,1],"test_size":0.5}
Expected: [5,5]
import numpy as np
from sklearn.model_selection import train_test_split
def split_sizes(X, y, test_size):
"""
Split the data and report how big each half is.
Args:
X: a 2-D feature array
y: a 1-D label array
test_size: the fraction to hold back, e.g. 0.2
Returns:
A list [n_train, n_test].
"""
# YOUR CODE HERE
passRun your code to see results
⌘↵ runs against the visible tests