Exercises
Train and Test Split
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
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
test_size=0.3, and set random_state so it is repeatable.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0
)
print(X_train.shape[0], X_test.shape[0])Exercise 2Passed
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()))One argument makes the split keep the proportions.
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, stratify=y)
print(int((y_test == 1).sum()))Exercise 3Passed
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
score() takes whichever pair you give it.
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(round(model.score(X_train, y_train), 2))
print(round(model.score(X_test, y_test), 2))