Chapters
Python114 chapters

Exercises

Features and Labels

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

Exercise 1

Split the DataFrame into X (the two measurements) and y (the species), then print their shapes.

Python needs pandas, scikit-learn, downloaded on first run
import pandas as pd

df = pd.DataFrame({
    "length": [5.1, 4.9, 6.2, 5.9],
    "width": [3.5, 3.0, 3.4, 3.0],
    "species": ["a", "a", "b", "b"],
})
# build X and y, then print X.shape and y.shape
Exercise 2

Take every column except the target, without naming the feature columns.

Python needs pandas, scikit-learn, downloaded on first run
import pandas as pd

df = pd.DataFrame({"a": [1, 2], "b": [3, 4], "target": [0, 1]})
# build X by dropping the target, then print its columns
Exercise 3

The target was left in the features, so the model cheats. Remove it and show the score drops.

Python needs pandas, scikit-learn, downloaded on first run
import pandas as pd
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier

df = pd.DataFrame({"noise": [1, 2, 3, 4, 5, 6, 7, 8], "target": [0, 1, 0, 1, 0, 1, 0, 1]})
y = df["target"]

X = df
print(round(cross_val_score(DecisionTreeClassifier(random_state=0), X, y, cv=4).mean(), 2))