首页 > 解决方案 > 管道和网格搜索的 SKLearn 错误

问题描述

我想首先将我的数据拆分为测试和训练集。然后我想在我的训练集上使用 GridSearchCV(内部分成训练/验证集)。最后我想收集所有的测试数据并做一些其他的事情(不在问题的范围内)。

我必须扩展我的数据。所以我想在管道中处理这个问题。我的 SVC 中的某些内容应该被修改(kernel='rbf', class_weight=...)。当我运行代码时,会发生以下情况:

“ValueError:估计器管道的参数估计器无效”

我不明白我做错了什么。我试图关注这个线程:StandardScaler with Pipelines and GridSearchCV

唯一的区别是,我在我的 SVC 中修复了一些参数。我该如何处理?

target = np.array(target).ravel()
loo = LeaveOneOut()
loo.get_n_splits(input)
    # Outer Loop
for train_index, test_index in loo.split(input):    
        X_train, X_test = input[train_index], input[test_index]
        y_train, y_test = target[train_index], target[test_index]
        p_grid = {'estimator__C': np.logspace(-5, 2, 20),}
                  'estimator__gamma': np.logspace(-5, 3, 20)}

        SVC_Kernel = SVC(kernel='rbf', class_weight='balanced',tol=10e-4, max_iter=200000, probability=False)
        pipe_SVC = Pipeline([('scaler',  RobustScaler()),('SVC', SVC_Kernel)])  
        n_splits = 5
        scoring = "f1_micro"

        inner_cv = StratifiedKFold(n_splits=n_splits,
                         shuffle=True, random_state=5)
        clfSearch = GridSearchCV(estimator=pipe_SVC, param_grid=p_grid,
                                 cv=inner_cv, scoring='f1_micro', iid=False, n_jobs=-1)

        clfSearch.fit(X_train, y_train)



        print("Best parameters set found on validation set for Support Vector Machine:")
        print()
        print(clfSearch.best_params_)
        print()
        print(clfSearch.best_score_)
        print("Grid scores on validation set:")
        print()

我也试过这样:

p_grid = {'estimator__C': np.logspace(-5, 2, 20),
              'estimator__gamma': np.logspace(-5, 3, 20),
              'estimator__tol': [10e-4],
              'estimator__kernel': ['rbf'],
              'estimator__class_weight': ['balanced'],
              'estimator__max_iter':[200000],
              'estimator__probability': [False]}

SVC_Kernel = SVC()

这也行不通。

标签: scikit-learnsvmpipelinegridsearchcv

解决方案


问题出在你的p_grid. 你在你的网格上搜索Pipeline,并且没有任何东西叫做estimator. 它确实有一个叫做 的东西SVC,所以如果你想设置它SVC的参数,你应该在你的键前面加上SVC__而不是estimator__。所以替换p_grid为:

p_grid = {'SVC__C': np.logspace(-5, 2, 20),}
          'SVC__gamma': np.logspace(-5, 3, 20)}

此外,您可以使用函数替换外for循环。cross_validate


推荐阅读