python-3.x - 如何在 scikit-learn 中访问管道 GridSearchCV 内估计器的属性?

标签 python-3.x machine-learning scikit-learn

我想访问 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/

相关文章:

python - 如何将这些数据转换为逻辑回归?

python - OpenCv错误无法通过视频捕获打开相机

python - 以特定格式提取 Excel 数据作为 python 文件的输入

python - 将 JSON 值转换为字符串

python - 如何使文本分类给出 None 类别

machine-learning - 狄利克雷过程中的质点、狄拉克三角洲

python - Python中具有正系数的线性回归

python - 带有TfidfVectorizer的ColumnTransformer产生 “empty vocabulary”错误

python - 尝试在 Mac 上使用 Python TestRail API - ImportError : No module named Conf_Reader

python - 如何在不使用 sklearn 的情况下在 Python 中计算 TPR 和 FPR?