管道和网格搜索的 SKLearn 错误

SKLearn Error with Pipeline and Gridsearch

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

我必须扩展我的数据。所以我想在管道中处理这个问题。我的 SVC 中的一些东西应该是 ficed (kernel='rbf', class_weight=...)。 当我 运行 出现以下代码时:

"ValueError: Invalid parameter estimator for estimator Pipeline"

我不明白我做错了什么。我试着关注这个话题:

唯一的区别是,我在我的 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()

这也不行。

问题出在您的 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)}

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