Menu
CoddyTech

随机森林

本课属于 Coddy Machine Learning 学习旅程的“监督学习”单元。第 41 课,共 58 课。

一棵决策树不够稳定:只要改动几行训练数据,它提出的问题就会变。这个章节会通过同时询问许多棵决策树,让结果更稳定。

随机森林会训练很多棵树,并让它们投票。这里有 7 棵树为一个间歇泉投票:

七棵小树排成一行,每棵树下方都有投票结果:是、是、否、是、是、否、是。箭头从每个投票结果指向一个写着“森林:是,5 票对 2 票”的方框

在代码中,还要再拟合一个模型:

from sklearn.ensemble import RandomForestClassifier

forest = RandomForestClassifier(n_estimators=100, random_state=0)
forest.fit(X_train, y_train)
print(forest.score(X_test, y_test))

在 300 个间歇泉日的数据上,这会输出 0.893,其中一棵树的得分是 0.813。n_estimators 表示树的数量。

选民越多,错误越少。

challenge icon

挑战

中等

导盲犬学校想尽早知道哪些幼犬能通过资格评定。起始代码会拆分 puppies.csv、评估一棵树,并读取树的数量。

  1. 训练一个包含指定数量树的森林(random_state=0),并输出其测试准确率。
  2. 输出哪个模型获胜以及领先多少,或者输出 A tie。

换一所学校,并使用 50:

Single tree: 0.740
Forest: 0.860
The forest wins by 0.120

然后试试 1:只有一棵树的森林表现出奇地差。下一课会解释原因。

亲手试试

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier

# 导盲犬学校的幼犬:平静程度、专注程度和听到巨响时的受惊程度(1 到 10),
# 体重、与寄养家庭相处的月数,以及是否具备导盲犬资格(是为 1,否为 0)
puppies = pd.read_csv("puppies.csv")
X = puppies[["calmness", "focus", "noise_startle", "weight_kg", "months_with_family"]]
y = puppies["qualified"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
trees = int(input())

# 不要修改下面的代码:你要超越这棵决策树
tree = DecisionTreeClassifier(random_state=0)
tree.fit(X_train, y_train)
tree_acc = tree.score(X_test, y_test)
print(f"Single tree: {tree_acc:.3f}")

# 在下方编写你的代码
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

监督学习中的所有课

自己练习: Python 在线编译器