python - RandomForestClassifier - 尝试识别 sklearn 中的特征重要性的奇怪错误?
问题描述
我正在尝试检索 RandomForestClassifier 模型中特征的重要性,检索模型中每个特征的系数,
我在这里运行以下代码,
random_forest = SelectFromModel(RandomForestClassifier(n_estimators = 200, random_state = 123))
random_forest.fit(X_train, y_train)
print(random_forest.estimator.feature_importances_)
但我收到以下错误
NotFittedError: This RandomForestClassifier instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.
我到底做错了什么?您可以看到我在确定特征的重要性之前就拟合了模型,但它似乎没有按应有的方式工作,
同样,我有下面带有 LogisticRegression 模型的代码,它工作正常,
log_reg = SelectFromModel(LogisticRegression(class_weight = "balanced", random_state = 123))
log_reg.fit(X_train, y_train)
print(log_reg.estimator_.coef_)
解决方案
您必须调用该属性estimator_
才能访问拟合的估计器(请参阅文档)。请注意您忘记了尾随_
。所以应该是:
print(random_forest.estimator_.feature_importances_)
有趣的是,您使用LogisticRegression
模型的示例正确地做到了。
推荐阅读
- javascript - Webpack JSX 无法通过 ES6 导入解析相关模块
- tensorflow - 模型预测 NaN
- javascript - 使用 JavaScript 编写一个将 2 个单独的构造函数作为参数的函数
- sql-server - 如何按数据从行到列分组
- python - colab 运行时死机,自动重启
- jquery - 添加新表行时重新加载 :gt() 选择器
- c# - 动态添加 css asp.net 页面
- java - 动态添加到clojure repl中的类路径以访问java类文件(石榴/添加类路径)
- json - scala parse json which has List of maps
- python-3.x - AttributeError:类型对象没有属性