如何让管道中的回归器解压参数?

2024-05-16 13:23:06 发布

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

所以我使用scikit学习管道来减少编写重复代码的步骤。但是,我看不出如何编写一个代码来解压每个回归器的参数。你知道吗

在使用管道之前,我编写了一个类来解压参数。虽然我相信有一个更好的方法来解决这个问题,但效果还不错。你知道吗

我不想继续手动编写参数

from sklearn.pipeline import make_pipeline
pipe_et = make_pipeline(StandardScaler(), ExtraTreesRegressor(n_estimators = 1000, random_state = Seed))
pipe_rf = make_pipeline(StandardScaler(), XGBRegressor())

这是我想要解包的参数的一个例子

rf_params = {'n_estimators': 1000, 'n_jobs': -1, 'warm_start': True, 'max_features':2}

没有错误。我不想做额外的劳动,但我希望**params工作,但我不知道如何继续。请帮助我的编码风格


Tags: 方法代码参数make管道pipeline步骤手动
2条回答

您需要使用__格式化估计器的参数,以便它可以作为管道的参数提供。我已经编写了一个小函数,可以为估计器获取管道和参数,然后它将为估计器返回适当的参数。你知道吗

请尝试以下示例:


from sklearn.pipeline import make_pipeline
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler

pipe_rf = make_pipeline(StandardScaler(), RandomForestRegressor())

rf_params = {'n_estimators': 10, 'n_jobs': -1, 'warm_start': True, 'max_features':2}

def params_formatter(pipeline, est_params):
    est_name = pipeline.steps[-1][0]
    return {'{}__{}'.format(est_name,k):v for k,v in est_params.items()}


params = params_formatter(pipe_rf, rf_params)
pipe_rf.set_params(**params)

# Pipeline(memory=None,
#          steps=[('standardscaler',
#                  StandardScaler(copy=True, with_mean=True, with_std=True)),
#                 ('randomforestregressor',
#                  RandomForestRegressor(bootstrap=True, criterion='mse',
#                                        max_depth=None, max_features=2,
#                                        max_leaf_nodes=None,
#                                        min_impurity_decrease=0.0,
#                                        min_impurity_split=None,
#                                        min_samples_leaf=1, min_samples_split=2,
#                                        min_weight_fraction_leaf=0.0,
#                                        n_estimators=10, n_jobs=-1,
#                                        oob_score=False, random_state=None,
#                                        verbose=0, warm_start=True))],
#          verbose=False)

您可以通过pipe_rf对象循环,得到如下参数:

for i in pipe_rf:
    print (i.get_params())

输出

{'copy': True, 'with_mean': True, 'with_std': True}
{'base_score': 0.5, 'booster': 'gbtree', 'colsample_bylevel': 1, 'colsample_bynode': 1, 'colsample_bytree': 1, 'gamma': 0, 'importance_type': 'gain', 'learning_rate': 0.1, 'max_delta_step': 0, 'max_depth': 3, 'min_child_weight': 1, 'missing': None, 'n_estimators': 100, 'n_jobs': 1, 'nthread': None, 'objective': 'reg:linear', 'random_state': 0, 'reg_alpha': 0, 'reg_lambda': 1, 'scale_pos_weight': 1, 'seed': None, 'silent': None, 'subsample': 1, 'verbosity': 1}

希望这有帮助!你知道吗

相关问题 更多 >