随机森林通过对训练数据随机抽样生成多个决策树,每个决策树都是根据随机选择的特征子集进行构建。在决策树的构建过程中,随机森林采用了自助采样(Bootstrap Sampling)和特征随机选择(Feature Randomness)的策略,使得每个决策树都具有一定的差异性。
在进行预测时,随机森林通过对每棵决策树的预测结果进行投票或平均来得到最终的预测结果。
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier # 生成随机数据集 X, y = make_classification(n_samples=100, n_features=2, n_informative=2, n_redundant=0, n_clusters_per_class=1, random_state=42) # 创建随机森林分类器 clf = RandomForestClassifier(n_estimators=100, random_state=42) # 在数据集上训练分类器 clf.fit(X, y) # 绘制决策边界 plt.figure(figsize=(8, 6)) # 生成网格点 xx, yy = np.meshgrid(np.linspace(-4, 4, 100), np.linspace(-4, 4, 100)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # 将预测结果可视化 Z = Z.reshape(xx.shape) plt.contourf(xx, yy, Z, alpha=0.8, cmap='RdYlBu') # 绘制数据点 plt.scatter(X[:, 0], X[:, 1], c=y, cmap='RdYlBu', edgecolor='k') plt.xlabel('Feature 1') plt.ylabel('Feature 2') plt.title('Random Forest Classifier Decision Boundary') plt.show()