读懂决策树
本课属于 Coddy Machine Learning 学习旅程的“监督学习”单元。第 28 课,共 58 课。
决策树中的问题是可读的,所以你可以检查它学到了什么。沿着鸢尾花树,查看一朵长 5.1 cm、宽 1.6 cm 的花:
export_text会以文本形式打印相同的问题,每个层级缩进一次:
from sklearn.tree import export_text
print(export_text(tree, feature_names=["petal_length", "petal_width"]))这会打印:
|--- petal_width <= 0.80
| |--- class: 0
|--- petal_width > 0.80
| |--- petal_length <= 4.95
| | |--- class: 1
| |--- petal_length > 4.95
| | |--- class: 2每一行只回答自己路径上的问题。第 2 类是 virginica,对于又长又宽的花瓣来说,这是一个合理的答案。
挑战
中等奶酪店的决策树会根据奶酪的含水量和熟成周数,将奶酪命名为 fresh、soft 或 hard。起始代码会训练这棵树,并读取一块新奶酪的数据。
- 打印决策树的问题和特征名称。
- 运行代码并阅读问题,然后补全
by_hand,让它用 if/else 提出相同的问题,并返回相同的答案。
打印结果中,对于一块被决策树判定为 soft 的奶酪:
By hand: soft
The tree: soft亲手试试
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text
# 每行对应一种奶酪:含水量(%)、熟成周数和奶酪种类
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)
# 一种需要命名的新奶酪
moisture = int(input())
aged = int(input())
new_cheese = pd.DataFrame([[moisture, aged]], columns=features)
# 在下方编写代码:先输出决策树,再在 by_hand 中按决策树的判断方式给出答案
def by_hand(moisture, aged):
return "fresh"
# 不要修改下面的代码行
print("By hand:", by_hand(moisture, aged))
print("The tree:", tree.predict(new_cheese)[0])
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
监督学习中的所有课
自己练习: Python 在线编译器