【问题标题】:House prices: Advanced regression techniques, Feature importance and Plot barplot of top 5 Feature Importances房价:高级回归技术、特征重要性和前 5 个特征重要性的图条形图
【发布时间】:2021-02-20 18:14:50
【问题描述】:

我正在做一个项目,我需要使用房价数据集绘制前 5 个特征重要性的条形图:高级回归技术,我使用以下方法计算了 RandomForest 回归器:

RF_model = RandomForestRegressor() 
  RF_model.fit(x,y)
  RF_model.score(x,y)
pred=RF_model.predict(df_test)
output=pd.DataFrame({'Id':Id, 'SalePrice':pred})
output.to_csv('output.csv', index=False)
output.head(5)

并且还使用以下代码计算了特征重要性

feature = pd.DataFrame(df_train.drop(['SalePrice', 'Id'], axis=1).columns, RF_model.feature_importances_)

现在我正在使用以下代码绘制前 5 个功能的条形图

f, ax = plt.subplots(figsize=(8, 6))
fig = sns.barplot(data = feature.sort_values(by = 'Coeff', ascending=False)[:5], x= 'Feature', y='Coeff')
plt.show();

但它给了我以下错误

KeyError Traceback(最近调用 最后)在 1 f, ax = plt.subplots(figsize=(8, 6)) ----> 2 fig = sns.barplot(data = feature.sort_values(by = 'Coeff', 升序=False)[:5], x= 'Feature', y='Coeff') 3 plt.show();

~\Anaconda3\lib\site-packages\pandas\core\frame.py 在 sort_values(self, by, 轴, 升序, 就地, 种类, na_position, 忽略索引)4925 4926 by = by [0] -> 4927 k = self._get_label_or_level_values(by, axis=axis) 4928 4929 if isinstance(ascending, (tuple, list)):

~\Anaconda3\lib\site-packages\pandas\core\generic.py 在 _get_label_or_level_values(self, key, axis) 1690 values = self.axes[axis].get_level_values(key)._values 1691 else: -> 1692 raise KeyError(key) 1693 1694 # 检查重复项

KeyError: 'Coeff'

有人可以帮我解决这个问题吗?提前谢谢你!

【问题讨论】:

    标签: python pandas jupyter-notebook


    【解决方案1】:

    您可以使用RF_model.feature_importances_ 访问已训练模型的feature_importances_ 属性。然后您可以根据需要绘制它们。查看sklearn.ensemble.RandomForestRegressor documentation 了解更多详细信息以及可用于访问模型的其他属性/方法。

    【讨论】:

    • 您能否建议最终的代码,以绘制条形图
    • 如果您可以提供指向您使用的数据集和您使用的其余代码(例如您的数据清理、训练-测试-拆分、包导入等)的链接,我可以试一试。 )。
    • 非常感谢!文件在笔记本文件夹中可用,以及此处的数据drive.google.com/drive/folders/…
    猜你喜欢
    • 1970-01-01
    • 2018-09-23
    • 2018-12-14
    • 2021-12-23
    • 2021-02-03
    • 2016-11-07
    • 1970-01-01
    • 2022-07-17
    • 2021-01-29
    相关资源
    最近更新 更多