前言
随机森林特征重要性条形图绘制,前几个特种呈现不同的颜色。
其中的误差棒是通过计算特征重要性的标准误差来获得的,以表示特征重要性的不确定性。标准误差是一种度量估计值的不确定性的统计量,它表示估计值可能偏离真实值的程度。
代码复现
"""
@Author: F娴熟
# -*- coding: utf-8 -*-
@FileName: 特征重要性条形图.py
@DateTime: 2023/10/7 11:18
@SoftWare: PyCharm
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
# 加载加利福尼亚房价数据集
data = fetch_california_housing()
X = data.data # 特征矩阵
y = data.target # 目标标签(房价)
# 创建随机森林回归模型
random_forest = RandomForestRegressor(n_estimators=100, random_state=42)
# 训练模型
random_forest.fit(X, y)
# 获取特征重要性分数
feature_importance = random_forest.feature_importances_
# 获取特征名称
feature_names = data.feature_names
# 计算特征重要性的标准误差
n_trees = len(random_forest.estimators_)
std_err = np.std([tree.feature_importances_ for tree in random_forest.estimators_], axis=0) / np.sqrt(n_trees)
# 排序特征重要性分数
sorted_idx = np.argsort(feature_importance)
# 创建一个颜色数组,前四个特征使用蓝色,后四个特征使用绿色
colors = ['#4477be' if i < 4 else '#fa8e8e' for i in range(len(sorted_idx))]
#设置误差棒颜色和大小
error_kw = {'ecolor': '#381da6', 'capsize': 4}
# 设置全局的字体大小和样式
plt.rcParams["font.size"] = 14
plt.rcParams["font.family"] = "Times New Roman"
plt.figure(figsize=(10,6), dpi=500)
# 去除外边框
plt.box(False)
# 添加竖线网格
plt.grid(axis='x', linestyle='--', alpha=0.7)
# 绘制条形图(带误差棒)
plt.barh(range(len(sorted_idx)), feature_importance[sorted_idx], xerr=std_err*5, align="center", height=0.5, color=colors, error_kw=error_kw)# 设置颜色
plt.yticks(range(len(sorted_idx)), [feature_names[i] for i in sorted_idx])
plt.xlabel("Characteristic importance")
plt.ylabel("Feature")
plt.title("Random forest features importance with Error Bars")
# 保存图片到本地
plt.savefig("RFimport.png")
plt.show()
结果展示
往期代码复现
更多代码请移步公众号获取(GIS探险家)
感谢大家花时间来阅读本文,小编水平有限,有失误之处请大家斧正!