首页 > 解决方案 > 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_)

标签: pythonscikit-learnsklearn-pandas

解决方案


您必须调用该属性estimator_才能访问拟合的估计器(请参阅文档)。请注意您忘记了尾随_。所以应该是:

print(random_forest.estimator_.feature_importances_)

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


推荐阅读