Chapters
Python114 chapters

Exercises

Your First Model

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

Exercise 1

Split the data, train a decision tree, and print its accuracy on the unseen part rounded to two places.

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

X, y = load_iris(return_X_y=True)
# split, fit, score
Exercise 2

This raises. Predict for the single flower without changing its measurements.

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(model.predict([5.1, 3.5, 1.4, 0.2]))
Exercise 3

Print the predicted species name rather than its number.

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)

prediction = model.predict([[6.5, 3.0, 5.5, 2.0]])[0]
# print the name