Menu
CoddyTech

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:

The iris tree as boxes with one path lit in orange: petal width 0.80 or less? No, 1.6. Petal length 4.95 or less? No, 5.1. The path ends at class 2

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: 2

Each row answers only the questions on its own path. Class 2 is virginica, a sensible answer for long, wide petals.

challenge icon

Challenge

Medium

A 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.

  1. Print the tree's questions with the feature names.
  2. Run it, read them, and complete by_hand so 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: soft

Try 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])
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Supervised Learning

Practice on your own: Online Python compiler