随机森林随机森林就是训练很多棵不同的决策树然后让它们投票决定最终结果。从何而来决策树很强大但有一个致命缺点容易过拟合。一棵树如果长得太深就会把噪声也学进去。为了克服这个缺点人们想了一个办法训练很多棵树每棵树用的数据略有不同每棵树用不同的特征子集这样单棵树可能会犯错但整个森林的投票结果会更稳定、更准确。代码import numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import load_irisfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_scorefrom collections import Counter 1. 准备数据 加载鸢尾花数据集iris load_iris()X iris.datay iris.target划分训练集和测试集X_train, X_test, y_train, y_test train_test_split(X, y, test_size0.3, random_state42) 2. 训练随机森林 创建包含 100 棵树的随机森林forest_model RandomForestClassifier(n_estimators100, # 100棵树max_depth5,random_state42)训练模型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 0single_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(f100棵树的投票明细: {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(f100棵树中有 {wrong_votes} 棵树投了反对票叛徒)随机森林分类判断客户会不会流失、图片属于哪一类回归预测房价、销量。它的优点准确率高、不容易过拟合、能处理大量特征、能评估特征重要性