You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

移除特征后重新计算Random Forest特征重要性报错如何修复

问题修复方案

错误原因

你训练随机森林模型时仅使用了3个特征,clfr.feature_importances_返回的是长度为3的重要性得分数组,但你生成Series时用的iris.feature_names是原始数据集自带的4个特征名列表,二者长度不匹配,因此触发ValueError。

修复方法

将生成特征重要性Series的代码行中的index参数,替换为你实际训练用的特征名列表即可,推荐直接调用特征数据集X的columns属性,后续调整特征时无需同步修改此处:

修改前代码

# determining feature importance (e.g. model participation)
feature_imp = pd.Series(clfr.feature_importances_,index=iris.feature_names).sort_values(ascending=False)

修改后代码

# determining feature importance (e.g. model participation)
feature_imp = pd.Series(clfr.feature_importances_,index=X.columns).sort_values(ascending=False)

如果需要手动指定也可以写成:

feature_imp = pd.Series(clfr.feature_importances_,index=['sepal length', 'petal length', 'petal width']).sort_values(ascending=False)

修改后代码即可正常运行,特征重要性的计算和可视化都会匹配你实际使用的3个特征。


内容的提问来源于stack exchange,提问作者Kyle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 23:06:02