在scikitlearn中,如何在转换的目标聚集管道中从经过训练的估计器访问属性?

2024-09-26 17:57:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我用scikit设置了一个小管道,了解我包装在一个TransforedTargetRegressor对象中。在训练之后,我想从我训练过的估计器中访问属性(例如feature_importances_)。谁能告诉我怎么做

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import MinMaxScaler
from sklearn.compose import TransformedTargetRegressor

# setup the pipeline
Pipeline(steps = [('scale', StandardScaler(with_mean=True, with_std=True)),
                  ('estimator', RandomForestRegressor())])

# tranform target variable
model = TransformedTargetRegressor(regressor=pipeline, 
                                   transformer=MinMaxScaler())
           
# fit model
model.fit(X_train, y_train)

我尝试了以下方法:

# try to access the attribute of the fitted estimator
model.get_params()['regressor__estimator'].feature_importances_
model.regressor.named_steps['estimator'].feature_importances_

但这会导致以下结果NotFittedError

NotFittedError: This RandomForestRegressor instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.


Tags: thefromimportmodelpipelinewithsklearnfeature
1条回答
网友
1楼 · 发布于 2024-09-26 17:57:09

当您查看^{}的文档时,它说属性.regressor_(注意后面的下划线)返回拟合的回归器。因此,您的呼叫应该如下所示:

model.regressor_.named_steps['estimator'].feature_importances_

您以前的呼叫只是返回一个未安装的克隆。这就是错误的来源

相关问题 更多 >

    热门问题