Exercises
Classification
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
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
export_text takes feature_names as a list.
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, export_text
data = load_iris()
model = DecisionTreeClassifier(max_depth=2, random_state=0).fit(data.data, data.target)
print(export_text(model, feature_names=list(data.feature_names)))Exercise 2Passed
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
feature_importances_ lines up with feature_names. max with a key, or zip and sort.
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
data = load_iris()
model = DecisionTreeClassifier(random_state=0).fit(data.data, data.target)
pairs = zip(data.feature_names, model.feature_importances_)
print(max(pairs, key=lambda pair: pair[1])[0])Exercise 3Passed
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
Both use the same fit and score calls.
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
)
for model in [DecisionTreeClassifier(random_state=0), KNeighborsClassifier()]:
model.fit(X_train, y_train)
print(round(model.score(X_test, y_test), 2))