包含了最简可行示例 😉
我想做的只是简单地使用 GridSearchCV 的参数来使用 Pipeline。
#我想使用 Pipeline 创建一个 SVM,并验证模型(测量准确度)
#import libraries
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import pandas as pd
#load test data
data = load_iris()
X_trainset, X_testset, y_trainset, y_testset = train_test_split(data['data'], data['target'], test_size=0.2)
#在这里我们准备 pipeline
pipeline = Pipeline([('scaler', StandardScaler()), ('SVM', SVC())])
grid = GridSearchCV(pipeline, param_grid={'SVM__gamma':[0.1,0.01]}, cv=5)
grid.fit(X_trainset, y_trainset) # (完成!现在我可以打印准确度和其他指标)
#现在我想将训练集和验证集组合起来,在部署前训练模型
#当然,我想使用 GridSearchCV 找到的最佳参数
big_x = np.concatenate([X_trainset,X_testset])
big_y = np.concatenate([y_trainset,y_testset])
到这里为止,一切正常。然后,我写了这一行:
model2 = pipeline.fit(big_x,big_y, grid.best_params_)
错误!
TypeError: fit() 需要 2 到 3 个位置参数,但提供了 4 个
然后我尝试更明确地表达:
model2 = pipeline.fit(big_x,big_y,fit_params=grid.best_params_)
又出错了!
ValueError: Pipeline.fit 不接受 fit_params 参数。您可以使用 stepname__parameter 格式向管道的特定步骤传递参数,例如 `Pipeline.fit(X, y, logisticregression__sample_weight=sample_weight)`。
然后我出于好奇尝试手动插入参数:
pipeline.fit(big_x,big_y, SVM__gamma= 0.01) #注意:我可能需要插入多个参数,而不仅仅是一个
又出错了 🙁
TypeError: fit() 接收到意外的关键字参数 'gamma'
我不明白为什么它找不到 gamma。我决定打印 pipeline.get_params() 来获得一些想法。
In [11]: print(pipeline.get_params())
Out [11]: {'memory': None, 'steps': [('scaler', StandardScaler(copy=True, with_mean=True, with_std=True)), ('SVM', SVC(C=1.0, break_ties=False, cache_size=200, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=3, gamma='scale', kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True,tol=0.001, verbose=False))], 'verbose': False, 'scaler': StandardScaler(copy=True, with_mean=True, with_std=True), 'SVM': SVC(C=1.0, break_ties=False, cache_size=200, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=3, gamma='scale', kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False), 'scaler__copy': True, 'scaler__with_mean': True, 'scaler__with_std': True, 'SVM__C': 1.0, 'SVM__break_ties': False, 'SVM__cache_size': 200, 'SVM__class_weight': None, 'SVM__coef0': 0.0, 'SVM__decision_function_shape': 'ovr', 'SVM__degree': 3, 'SVM__gamma': 'scale', 'SVM__kernel': 'rbf', 'SVM__max_iter': -1, 'SVM__probability': False, 'SVM__random_state': None, 'SVM__shrinking': True, 'SVM__tol': 0.001, 'SVM__verbose': False}
我能在列表中找到 SVM__gamma!那为什么会出错呢?
Scikit 版本:0.22.1
Python 版本:3.7.6
回答:
.fit()
,即对 SVC 类的 .fit()
函数的调用,没有名为 gamma 的参数。当你调用 pipeline.fit(SVM__gamma)
时,它会将 gamma 参数传递给 SVM 步骤的 .fit()
调用,这是不起作用的。
在 scikit-learn 中,你可以使用 .set_params() 函数来设置参数。在最低层次(即对 SVC 本身),你可以简单地使用 SVC.set_params(gamma='blah')
。在 pipeline 中,你可以使用你在参数网格中使用的双下划线符号,所以是 pipeline.set_params(SVM__gamma=blah)
,
如果你只是对 pipeline 的单个步骤设置一个参数,通常直接访问步骤会很方便,例如 pipeline.named_steps.SVM.set_params(gamma='blah')
,或者使用 pipeline.set_params(**grid.best_params_)
来使用你的网格搜索的最佳参数。(** 符号会将 {‘A’:1, ‘B’:2} 这样的字典展开成 A=1, B=2)
这里是一个脚本片段,展示了我认为你想做的事情(尽管使用了不同的算法):
# 将分类器设置为 XGBClassifier
clf_pipeline = Pipeline(
steps=[
('preprocessor', preprocessor),
('classifier', XGBClassifier(n_jobs=6, n_estimators=20))
])
# In[41]:
# 交叉验证:60 次迭代,3 折 CV。
n_features_after_transform = clf_pipeline.named_steps.preprocessor.fit_transform(df).shape[1]
param_grid = {
'classifier__max_depth':stats.randint(low=2, high=100),
'classifier__max_features':stats.randint(low=2, high=n_features_after_transform),
'classifier__gamma':stats.uniform.rvs(0, 0.25, size=10000),
'classifier__subsample':stats.uniform.rvs(0.5, 0.5, size=10000),
'classifier__reg_alpha':stats.uniform.rvs(0.5, 1., size=10000),
'classifier__reg_lambda':stats.uniform.rvs(0.5, 1., size=10000)}
rscv = RandomizedSearchCV(
clf_pipeline,
param_grid,
n_iter=60,
scoring='roc_auc',
cv=StratifiedKFold(n_splits=3, shuffle=True))
rscv.fit(df, y)
# In[42]:
# 设置调优后的最佳参数,并增加估计器数量。
clf_pipeline.set_params(**rscv.best_params_)
clf_pipeline.named_steps.classifier.set_params(n_estimators=200)
长话短说,你可以通过访问 pipeline 的 named_steps
来设置单个参数。要设置你的网格搜索确定的最佳参数,使用 pipeline.set_params(**grid.best_params_)