Exercises
Your First Model
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
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
train_test_split returns X_train, X_test, y_train, y_test in that order.
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)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
model = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print(round(model.score(X_test, y_test), 2))Exercise 2Passed
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]))predict wants rows, so one example still needs an outer pair of brackets.
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 3Passed
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
data.target_names maps the number back to a name. Wrap it in str() to print it plainly.
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(str(data.target_names[prediction]))