sklearn.ensemble.RandomForestRegressor
(随机森林回归器)
RandomForestRegressor
是 sklearn.ensemble
提供的 随机森林(Random Forest)回归模型,通过 集成多棵决策树 进行回归预测,提高模型稳定性,减少过拟合,适用于 非线性回归任务。
1. RandomForestRegressor
作用
- 用于回归任务(如 房价预测、股票趋势分析)。
- 通过多个决策树组合,提高预测精度。
- 减少过拟合,适用于高维数据和非线性数据。
2. RandomForestRegressor
代码示例
(1) 训练随机森林回归器
from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
# 生成回归数据
X, y = make_regression(n_samples=100, n_features=1, noise=10, random_state=42)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练随机森林回归模型
model = RandomForestRegressor(n_estimators=100, max_depth=3, random_state=42)
model.fit(X_train, y_train)
# 预测
y_pred = model.predict(X_test)
# 计算 R²
r2 = model.score(X_test, y_test)
print("随机森林回归器 R²:", r2)
解释
n_estimators=100
:使用100
棵决策树,提高稳定性。max_depth=3
:限制树的深度,防止过拟合。random_state=42
:保证结果可复现。
3. RandomForestRegressor
主要参数
RandomForestRegressor(n_estimators=100, criterion="squared_error", max_depth=None, min_samples_split=2, min_samples_leaf=1, bootstrap=True, random_state=None)
参数 | 说明 |
---|---|
n_estimators | 决策树数量(默认 100 ,值越大,模型越稳定但训练时间增加) |
criterion | “squared_error”(默认) or “absolute_error”(均方误差/绝对误差) |
max_depth | 每棵树的最大深度(默认 None ,自动生长) |
min_samples_split | 分裂内部节点的最小样本数(默认 2 ) |
min_samples_leaf | 叶子节点的最小样本数(默认 1 ) |
bootstrap | 是否使用自助采样(默认 True ) |
random_state | 设置随机种子,保证结果可复现 |
4. 获取特征重要性
import numpy as np
feature_importances = model.feature_importances_
print("特征重要性:", feature_importances)
解释
feature_importances_
返回每个特征的重要性(数值越大,该特征越关键)。
5. 计算模型性能
from sklearn.metrics import mean_squared_error, r2_score
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("均方误差 MSE:", mse)
print("决定系数 R²:", r2)
解释
- MSE(均方误差):值越小,拟合效果越好。
- R²(决定系数):
1
表示完美拟合,0
表示无解释能力。
6. RandomForestRegressor
vs. DecisionTreeRegressor
模型 | 适用情况 | 主要区别 |
---|---|---|
DecisionTreeRegressor | 单棵决策树回归 | 易过拟合,适合小数据 |
RandomForestRegressor | 多个决策树投票 | 减少过拟合,提高泛化能力 |
示例
from sklearn.tree import DecisionTreeRegressor
tree_model = DecisionTreeRegressor(max_depth=3, random_state=42)
tree_model.fit(X_train, y_train)
print("决策树回归器 R²:", tree_model.score(X_test, y_test))
print("随机森林回归器 R²:", model.score(X_test, y_test))
解释
- 随机森林比单棵决策树泛化能力更强。
7. n_estimators
对模型的影响
import numpy as np
estimators = [10, 50, 100, 200]
for n in estimators:
model = RandomForestRegressor(n_estimators=n, max_depth=3, random_state=42)
model.fit(X_train, y_train)
print(f"n_estimators={n}, 测试集 R²={model.score(X_test, y_test)}")
解释
- 较小的
n_estimators
(如10
)不够稳定。 - 较大的
n_estimators
(如200
)更稳定,但计算时间变长。
8. 适用场景
- 回归任务(如 房价预测、能源消耗预测)。
- 数据具有非线性关系,线性模型无法有效拟合。
- 需要可解释性强的模型(特征重要性分析)。
9. 结论
RandomForestRegressor
适用于回归任务,基于多个决策树投票,提高预测准确率,比 单棵决策树泛化能力更强,适用于 非线性数据和高维数据。