sklearn.ensemble.RandomForestClassifier
(随机森林分类器)
RandomForestClassifier
是 sklearn.ensemble
提供的 随机森林(Random Forest)分类模型,它通过 集成多棵决策树 提高分类性能,减少过拟合,适用于 分类任务。
1. RandomForestClassifier
作用
- 用于分类任务(如垃圾邮件检测、图像分类)。
- 通过多个决策树投票,提高分类准确率。
- 减少过拟合,泛化能力强。
2. RandomForestClassifier
代码示例
(1) 训练随机森林分类器
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# 加载数据
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)
# 训练随机森林分类器
model = RandomForestClassifier(n_estimators=100, max_depth=3, random_state=42)
model.fit(X_train, y_train)
# 预测
y_pred = model.predict(X_test)
# 计算准确率
accuracy = model.score(X_test, y_test)
print("准确率:", accuracy)
解释
n_estimators=100
:使用100
棵决策树,提高稳定性。max_depth=3
:限制每棵树的深度,防止过拟合。random_state=42
:保证结果可复现。
3. RandomForestClassifier
主要参数
RandomForestClassifier(n_estimators=100, criterion="gini", max_depth=None, min_samples_split=2, min_samples_leaf=1, bootstrap=True, random_state=None)
参数 | 说明 |
---|---|
n_estimators | 森林中的决策树数量(默认 100 ) |
criterion | “gini”(默认) or “entropy”(基尼指数/信息增益) |
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_
feature_names = iris.feature_names
# 输出特征重要性
for name, importance in zip(feature_names, feature_importances):
print(f"{name}: {importance:.4f}")
解释
feature_importances_
返回每个特征的重要性(数值越大,该特征越重要)。
5. 计算模型性能
from sklearn.metrics import classification_report
print("分类报告:\n", classification_report(y_test, y_pred))
解释
- 计算精确率、召回率和 F1 分数。
6. 决策树可视化
from sklearn.tree import plot_tree
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 8))
plot_tree(model.estimators_[0], feature_names=iris.feature_names, class_names=iris.target_names, filled=True)
plt.show()
解释
model.estimators_[0]
选择森林中的第一棵树进行可视化。
7. RandomForestClassifier
vs. DecisionTreeClassifier
模型 | 适用情况 | 主要区别 |
---|---|---|
DecisionTreeClassifier | 单棵决策树 | 易过拟合,适合小数据 |
RandomForestClassifier | 多个决策树投票 | 减少过拟合,泛化能力更强 |
示例
from sklearn.tree import DecisionTreeClassifier
tree_model = DecisionTreeClassifier(max_depth=3, random_state=42)
tree_model.fit(X_train, y_train)
print("决策树准确率:", tree_model.score(X_test, y_test))
print("随机森林准确率:", model.score(X_test, y_test))
解释
- 随机森林比单棵决策树泛化能力更强。
8. 适用场景
- 分类任务(如 信用评分、垃圾邮件检测)。
- 数据具有一定噪声,单棵决策树可能过拟合。
- 需要特征选择,分析哪些特征更重要。
9. 结论
RandomForestClassifier
适用于分类任务,基于多个决策树投票,提高分类准确率,支持 特征重要性分析,可视化决策树结构,比 单棵决策树泛化能力更强。