基于树的模型:决策树与随机森林
构建并调优决策树和集成森林模型。
基于树的模型:决策树与随机森林 是 CoddyKit 上的免费 Python Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Python Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Python Academy 课程共包含 4 节课。
决策树概念
决策树通过提出一系列二元问题,将数据划分为多个子集。每个内部节点表示一个特征阈值,每个叶节点表示一个预测结果。
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
model = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X, y)
print("Depth:", model.get_depth())
print("Leaves:", model.get_n_leaves())DecisionTreeClassifier
关键超参数包括:max_depth、min_samples_split 和 min_samples_leaf。树越深越容易过拟合,树越浅越容易欠拟合。
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
model = DecisionTreeClassifier(max_depth=5, min_samples_leaf=5)
model.fit(X_tr, y_tr)
print("Test acc:", model.score(X_te, y_te))DecisionTreeRegressor
决策树同样可以处理回归问题,方法是在每个叶节点中预测目标值的平均值。
from sklearn.tree import DecisionTreeRegressor
from sklearn.datasets import make_regression
from sklearn.metrics import mean_squared_error
X, y = make_regression(noise=15, random_state=0)
model = DecisionTreeRegressor(max_depth=4).fit(X, y)
print("RMSE:", mean_squared_error(y, model.predict(X))**0.5)特征重要性
model.feature_importances_ 根据不纯度减少量,给出每个特征的相对重要性。
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
import numpy as np
X, y = load_iris(return_X_y=True)
feature_names = load_iris().feature_names
model = DecisionTreeClassifier().fit(X, y)
for name, imp in sorted(zip(feature_names, model.feature_importances_), key=lambda x: -x[1]):
print(f"{name}: {imp:.3f}")随机森林概览
随机森林在自助采样数据上训练许多彼此不相关的决策树,并对它们的预测结果取平均,从而降低方差而不会增加偏差。
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
model = RandomForestClassifier(n_estimators=100, random_state=0)
model.fit(X_tr, y_tr)
print("Test acc:", model.score(X_te, y_te))RandomForestRegressor
随机森林同样适用于回归问题。
from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import make_regression
from sklearn.metrics import r2_score
X, y = make_regression(noise=10, random_state=0)
model = RandomForestRegressor(n_estimators=100, random_state=0).fit(X, y)
print("R²:", r2_score(y, model.predict(X)))袋外得分
设置 oob_score=True,即可使用未出现在每棵树自助采样中的样本获得免费的验证得分,无需单独的测试集。
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
X, y = make_classification(random_state=0)
model = RandomForestClassifier(n_estimators=100, oob_score=True, random_state=0).fit(X, y)
print("OOB score:", model.oob_score_)梯度提升
梯度提升(GBM)按顺序训练多棵树,每棵树都纠正前一棵树产生的错误。它通常比随机森林更准确,但训练速度更慢。
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
model = GradientBoostingClassifier(n_estimators=100).fit(X_tr, y_tr)
print("Test acc:", model.score(X_te, y_te))XGBoost / LightGBM
XGBoost 和 LightGBM 是经过优化的梯度提升库,比 sklearn 的 GBM 速度更快、扩展性更好,而且通常也更准确。
# pip install xgboost lightgbm
from xgboost import XGBClassifier
from lightgbm import LGBMClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
xgb = XGBClassifier(n_estimators=100, eval_metric="logloss").fit(X_tr, y_tr)
print("XGB acc:", xgb.score(X_te, y_te))调整 n_estimators
在一定范围内,随机森林中的树越多,方差越低,同时不会导致过拟合。请使用验证曲线找出最佳树数量。
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.datasets import make_classification
import numpy as np
X, y = make_classification(random_state=0)
for n in [10, 50, 100, 200]:
scores = cross_val_score(RandomForestClassifier(n_estimators=n, random_state=0), X, y, cv=5)
print(f"n={n}: {scores.mean():.3f}")可视化决策树
使用 sklearn.tree.plot_tree 或 export_text 检查决策树学到了什么。
from sklearn.tree import DecisionTreeClassifier, export_text, plot_tree
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
model = DecisionTreeClassifier(max_depth=2).fit(X, y)
print(export_text(model, feature_names=load_iris().feature_names.tolist()))快速检查
与单棵决策树相比,随机森林如何减少过拟合?
回顾
决策树根据特征阈值划分数据,并使用叶节点值进行预测。调整 max_depth 来控制过拟合。随机森林对许多棵树的结果取平均,以降低方差。梯度提升按顺序训练多棵树,以获得较高的准确率。在生产环境中,建议优先使用 XGBoost 或 LightGBM。
常见问题解答
「基于树的模型:决策树与随机森林」课时是免费的吗?
是的 — 「基于树的模型:决策树与随机森林」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Python Academy 课程的其余内容,请升级到 CoddyKit PRO。 Python Academy 课程共包含 4 节课。
「基于树的模型:决策树与随机森林」这节课中我会学到什么?
构建并调优决策树和集成森林模型。 你通过在浏览器中直接运行的动手代码来练习 Python Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Python Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Python Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「基于树的模型:决策树与随机森林」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Python Academy 课中编写并运行代码吗?
能。每节 Python Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- scikit-learn API:fit、transform、predict
- 线性模型:回归与分类
- 基于树的模型:决策树与随机森林
- 模型评估与交叉验证