随机森林:
随机森林就是训练很多棵不同的决策树,然后让它们投票决定最终结果。
从何而来:
决策树很强大,但有一个致命缺点:容易过拟合。一棵树如果长得太深,就会把噪声也学进去。
为了克服这个缺点,人们想了一个办法:
训练很多棵树
每棵树用的数据略有不同
每棵树用不同的特征子集
这样,单棵树可能会犯错,但整个森林的投票结果会更稳定、更准确。
代码:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from collections import Counter
================= 1. 准备数据 =================
加载鸢尾花数据集
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
)
================= 2. 训练随机森林 =================
创建包含 100 棵树的随机森林
forest_model = RandomForestClassifier(
n_estimators=100, # 100棵树
max_depth=5,
random_state=42
)
训练模型
forest_model.fit(X_train, y_train)
预测并评估准确率
forest_pred = forest_model.predict(X_test)
forest_acc = accuracy_score(y_test, forest_pred)
print(f"随机森林在测试集上的准确率:{forest_acc:.3f}\n")
================= 3. 画出特征重要性 =================
importances = forest_model.feature_importances_
plt.figure(figsize=(8, 5))
plt.barh(iris.feature_names, importances)
plt.xlabel(‘特征重要性’)
plt.title(‘随机森林:哪些特征更重要’)
plt.grid(True)
plt.show()
================= 4. 终极透视:100棵树的投票过程 =================
1. 挑出测试集的第 1 个样本(一朵花)
sample_index = 0
single_X = X_test[sample_index].reshape(1, -1) # 取出这 1 朵花
true_label = y_test[sample_index] # 它的真实品种
2. 【核心大招】让森林里的 100 棵树,各自对这朵花进行预测!
estimators_ 里面才真正装着那 100 棵独立的树
all_votes = [tree.predict(single_X)[0] for tree in forest_model.estimators_]
3. 统计这 100 棵树的票数
vote_counts = Counter(int(v) for v in all_votes)
print(f"真实品种: {iris.target_names[true_label]}“)
print(f"100棵树的投票明细: {dict(vote_counts)}”)
4. 找出得票最多的冠军
winner = vote_counts.most_common(1)[0][0]
print(f"最终获胜结果: {iris.target_names[winner]}")
5. 看看有没有“叛徒”(投错票的树)
wrong_votes = sum(1 for v in all_votes if v != winner)
print(f"100棵树中有 {wrong_votes} 棵树投了反对票(叛徒)!")
随机森林:分类:判断客户会不会流失、图片属于哪一类
回归:预测房价、销量。
它的优点:准确率高、不容易过拟合、能处理大量特征、能评估特征重要性