AttributeError Traceback most recent call lastCell In36 line 5 3 import matplotlibfont_manager as fm 4 pltrcParamsfontsans-serif=SimHei---- 5 importances = pltfeat
出错原因:matplotlib.pyplot模块没有feature_importances_属性。
修改如下:
-
首先,需要使用sklearn.ensemble中的RandomForestRegressor或RandomForestClassifier来训练模型并获取特征重要性。
-
然后,使用模型的feature_importances_属性获取特征重要性。
修改后的代码如下:
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor # 或者 RandomForestClassifier
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
plt.rcParams['font.sans-serif']=['SimHei']
# 加载数据
data = pd.read_csv('data.csv')
X = data.drop('target', axis=1)
y = data['target']
# 训练模型并获取特征重要性
model = RandomForestRegressor() # 或者 RandomForestClassifier()
model.fit(X, y)
importances = model.feature_importances_
# 绘制特征重要性图
labels = X.columns.values
plt.bar(np.arange(len(labels)), importances)
plt.xticks(np.arange(len(labels)), labels, rotation=90)
plt.xlabel('特征')
plt.ylabel('重要性')
plt.title('特征重要性图')
plt.show()
``
原文地址: https://www.cveoy.top/t/topic/hsqG 著作权归作者所有。请勿转载和采集!