【问题标题】:RandomForestClassifier - Odd error with trying to identify feature importance in sklearn?RandomForestClassifier - 尝试识别 sklearn 中的特征重要性的奇怪错误?
【发布时间】:2020-11-04 00:44:50
【问题描述】:

我正在尝试检索 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_)

【问题讨论】:

    标签: python scikit-learn sklearn-pandas


    【解决方案1】:

    您必须调用属性estimator_ 才能访问fitted 估计器(请参阅docs)。请注意,您忘记了结尾的 _。所以应该是:

    print(random_forest.estimator_.feature_importances_)
    

    有趣的是,您使用 LogisticRegression 模型为您的示例正确地做到了。

    【讨论】:

    • 哦,哇!我胖手指并删除了估算器后的_!谢谢!
    猜你喜欢
    • 2016-02-23
    • 2021-09-02
    • 2014-02-17
    • 2020-03-02
    • 2019-11-05
    • 2019-05-30
    • 2021-08-22
    • 1970-01-01
    • 2019-08-10
    相关资源
    最近更新 更多