Reading a Tree
Part of the Supervised Learning section of Coddy's Machine Learning journey. Lesson 28 of 58.
A tree's questions are readable, so you can check what it learned. Follow a flower 5.1 cm long and 1.6 cm wide down the iris tree:
export_text prints the same questions as text, one indent per level:
from sklearn.tree import export_text
print(export_text(tree, feature_names=["petal_length", "petal_width"]))This prints:
|--- petal_width <= 0.80
| |--- class: 0
|--- petal_width > 0.80
| |--- petal_length <= 4.95
| | |--- class: 1
| |--- petal_length > 4.95
| | |--- class: 2Each row answers only the questions on its own path. Class 2 is virginica, a sensible answer for long, wide petals.
Challenge
MediumA cheese shop's tree names a cheese, fresh, soft or hard, from its water content and its weeks of aging. The starter trains it and reads a new cheese.
- Print the tree's questions with the feature names.
- Run it, read them, and complete
by_handso it asks the same questions with if/else and returns the same answer.
After the printout, for a cheese the tree calls soft:
By hand: soft
The tree: softTry it yourself
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text
# One row per cheese: water content (%), weeks of aging, and its kind
cheeses = pd.read_csv("cheeses.csv")
features = ["moisture_pct", "aged_weeks"]
X_train, X_test, y_train, y_test = train_test_split(cheeses[features], cheeses["cheese"], test_size=0.25, random_state=0)
tree = DecisionTreeClassifier(max_depth=2, random_state=0)
tree.fit(X_train, y_train)
# A new cheese to name
moisture = int(input())
aged = int(input())
new_cheese = pd.DataFrame([[moisture, aged]], columns=features)
# Write your code below: print the tree, then answer in by_hand the way it does
def by_hand(moisture, aged):
return "fresh"
# Don't change the lines below
print("By hand:", by_hand(moisture, aged))
print("The tree:", tree.predict(new_cheese)[0])
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Supervised Learning
1Your First Model
Learning from ExamplesTrain and Test SetsFit and PredictScoring a ModelRecap: Seed Sorter2Nearest Neighbors
How k-NN DecidesChoosing kDecision BoundariesScaling for NeighborsRecap: Wine Neighbors5Measuring Classifiers
The Confusion MatrixPrecision and RecallThe F1 ScoreImbalanced ClassesROC CurvesRecap: Screening Test11Project: Penguin Species
Meet the PenguinsPrepare the DataChoose a ModelTune the WinnerShip the ModelPractice on your own: Online Python compiler