Chapters
Python114 chapters

Exercises

Train and Test Split

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Split into 70% training and 30% test, reproducibly, and print both row counts.

Python needs scikit-learn, downloaded on first run
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

X, y = load_iris(return_X_y=True)
# split and print the two sizes
Exercise 2

Keep the class balance in both halves, and print how many of the rare class are in the test set.

Python needs scikit-learn, downloaded on first run
import numpy as np
from sklearn.model_selection import train_test_split

y = np.array([0] * 90 + [1] * 10)
X = np.arange(100).reshape(-1, 1)

_, _, _, y_test = train_test_split(X, y, test_size=0.2, random_state=3)
print(int((y_test == 1).sum()))
Exercise 3

Print the training score and the test score, to show the gap.

Python needs scikit-learn, downloaded on first run
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=0, stratify=y
)
model = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
# print both scores, each rounded to two places