Chapters
Python114 chapters

Exercises

Classification

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

Exercise 1

Print the tree's rules, limited to a depth of two, with the real feature names.

Python needs scikit-learn, downloaded on first run
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, export_text

data = load_iris()
# fit a depth-2 tree and print its rules
Exercise 2

Print which feature the tree relies on most.

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

data = load_iris()
model = DecisionTreeClassifier(random_state=0).fit(data.data, data.target)
# print the name of the most important feature
Exercise 3

Compare a decision tree and k nearest neighbours on the same split, printing both accuracies.

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

X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=0, stratify=y
)
# fit both and print each score to two places