随机森林(Random Forest)是一种基于决策树的集成学习方法,由多个独立训练的决策树组成,能够显著提升模型的性能和稳定性。它通过引入随机性,增强了模型的泛化能力。随机森林通常用于分类和回归问题。
随机森林的工作原理
- 随机采样:使用自助采样法(Bootstrap Sampling),即有放回的随机抽样,创建多个样本数据集。
- 构建决策树:对每个样本数据集构建一棵决策树,在节点分裂时,随机选择特征的子集进行最佳分裂。
- 集成预测:
- 分类问题:采用投票方式,选择得票最多的类别作为预测结果。
- 回归问题:取多个决策树预测值的平均值作为最终预测结果。
Python 实现:随机森林
我们可以使用 scikit-learn
库实现随机森林。下面是一个分类问题的具体案例:
案例分析:使用随机森林进行鸢尾花分类
数据集:鸢尾花数据集(Iris Dataset)
Python 实现:
# 导入所需库
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
import seaborn as sns
import matplotlib.pyplot as plt
# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 使用随机森林进行分类
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
# 预测测试集
y_pred = rf.predict(X_test)
# 输出分类报告和混淆矩阵
print("Classification Report:")
print(classification_report(y_test, y_pred, target_names=iris.target_names))
print("Confusion Matrix:")
cm = confusion_matrix(y_test, y_pred)
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues", xticklabels=iris.target_names, yticklabels=iris.target_names)
plt.xlabel("Predicted")
plt.ylabel("Actual")
plt.show()
# 输出准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")
# 绘制特征重要性
feature_importances = rf.feature_importances_
features = iris.feature_names
sns.barplot(x=feature_importances, y=features)
plt.xlabel("Feature Importance Score")
plt.ylabel("Features")
plt.title("Feature Importance in Random Forest")
plt.show()
案例分析:使用随机森林进行回归
数据集:加州房价数据集(California Housing Dataset)
Python 实现:
# 导入所需库
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# 加载加州房价数据集
california = fetch_california_housing()
X = california.data
y = california.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 使用随机森林进行回归
rf = RandomForestRegressor(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
# 预测测试集
y_pred = rf.predict(X_test)
# 输出性能指标
mse = mean_squared_error(y_test, y_pred)
mae = mean_absolute_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)