梯度提升
本课属于 Coddy Machine Learning 学习旅程的“监督学习”单元。第 43 课,共 58 课。
森林里的树并排生长。梯度提升则让树一棵接一棵地生长:每棵新树都会学习之前的树仍然预测错误的内容。
这里用一棵棵树来拟合冰沙吧的销售额:
对于分类任务,模型是 GradientBoostingClassifier:
from sklearn.ensemble import GradientBoostingClassifier
boost = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, random_state=0)
boost.fit(X_train, y_train)learning_rate 设置每次修正保留多少。步子小一些更稳妥,因此需要更多棵树。
挑战
中等一位兰花种植者想知道哪些植株会开花。起始代码会拆分 orchids.csv,评估随机森林,并读取树的数量。
- 对
rates中的每个学习率,使用对应数量的树训练提升模型(random_state=0),并输出其测试准确率。 - 输出最佳学习率。如果出现并列,保留较早的那个。
换一位种植者,并输入 20:
Forest: 0.860
Boosting at rate 0.01: 0.600
Boosting at rate 0.1: 0.860
Boosting at rate 1.0: 0.900
Best rate for 20 trees: 1.0然后试试几个不同的树数量:提升模型什么时候会胜过随机森林?
亲手试试
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
# 种植者架上的兰花:今年开花(1)或未开花(0)
orchids = pd.read_csv("orchids.csv")
X = orchids.drop(columns="bloomed")
y = orchids["bloomed"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
trees = int(input())
rates = [0.01, 0.1, 1.0]
# 不要修改下面的代码:这是用于比较的随机森林模型
forest = RandomForestClassifier(n_estimators=100, random_state=0)
forest.fit(X_train, y_train)
print(f"Forest: {forest.score(X_test, y_test):.3f}")
# 在下面编写你的代码
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
监督学习中的所有课
自己练习: Python 在线编译器