我想访问 DecisionTreeRegressor 的 feature_importances_ 属性 在下面的代码中:
#Create an estimator
from sklearn.tree import DecisionTreeRegressor
tree_reg = DecisionTreeRegressor(criterion='mse', random_state=0)
#Create parametre grid for GridSearchCV
param_grid = { 'max_depth':np.linspace(start=4, stop=12, num=9),
'max_leaf_nodes':[i for i in range(10,20,1)]}
# Construct gridsearchcv on param space
from sklearn.model_selection import ShuffleSplit
from sklearn.model_selection import GridSearchCV
cv = ShuffleSplit(n_splits=10, test_size=0.30, random_state=0)
grid = GridSearchCV(estimator=tree_reg, param_grid=param_grid, cv=cv, refit=True)
#Make Pipeline
from sklearn.pipeline import Pipeline
pipe = Pipeline(steps=[('preprocess', StandardScaler()), ('grid_search', grid)])
pipe.fit(X_train, y_train)
feat_impo = tree_reg.feature_importances_ #getting ERROR on this line
我想访问 DecisionTreeRegressor 的 feature_importances_ 属性,但在执行 tree_reg.feature_importances_ 时出现以下错误:
sklearn.exceptions.NotFittedError: This DecisionTreeRegressor instance is
not fitted yet. Call 'fit' with appropriate arguments before using this method.
我也尝试过这个:
grid.__getattribute__('estimator').feature_importances_
但我得到了完全相同的结果。
但是当我在没有管道和网格搜索的情况下运行程序时,即仅
使用 DecisionTreeRegressor 然后我可以使用 tree_reg.feature_importances_
轻松访问 feature_importances_ 并获得理想的结果,没有任何错误。
如何访问 DecisionTreeRegressor 的 feature_importances_ 属性?
最佳答案
终于找到正确的方法了
best_est = grid.best_estimator_
feat_impo = best_est.feature_importances_
关于python-3.x - 如何在 scikit-learn 中访问管道 GridSearchCV 内估计器的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57221264/