使用组进行预测的巢式交叉验证

问题描述 投票:2回答:1

我无能为力,我想知道这是错误还是正常方式。

我正在尝试对数据集进行嵌套交叉验证,并且每个交叉验证都属于一个患者。为避免对同一位患者进行学习和测试,我发现您实施了一种“组”机制,在我的情况下,GroupKFold似乎是正确的。当我的分类器得到不同的参数时,我进入GridSearchCv来修复模型的超级参数。同样,我认为测试/培训必须属于不同的患者。

(对于那些对嵌套交叉验证感兴趣的人:http://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html]

我以这种方式进行:

pipe = Pipeline([('pca', PCA()),
                 ('clf', SVC()),
                 ])
# Find the best parameters for both the feature extraction and the classifier
grid_search = GridSearchCV(estimator=pipe, param_grid=some_param, cv=GroupKFold(n_splits=5), verbose=1)
grid_search.fit(X=features, y=labels, groups=groups)

# Nested CV with parameter optimization
predictions = cross_val_predict(grid_search, X=features, y=labels, cv=GroupKFold(n_splits=5), groups=groups)

并获得一些:

File : _split.py", line 489, in _iter_test_indices
    raise ValueError("The 'groups' parameter should not be None.")
ValueError: The 'groups' parameter should not be None.

在代码中,_fit_and_predict()方法似乎未将组共享给估计器,因此,无法使用所需的组。

我可以提供一些线索吗?祝你今天愉快,最好的问候

python scikit-learn
1个回答
0
投票

我有同样的问题,除了以更实际的方式实现它之外,我找不到其他方法:

outer_cv = GroupKFold(n_splits=4).split(X_data, y_data, groups=groups)
nested_cv_scores = []
for train_ids, test_ids in outer_cv:
    inner_cv = GroupKFold(n_splits=4).split(X_data[train_ids, :], y_data.iloc[train_ids], groups=groups[train_ids])

    rf = RandomForestClassifier()
    rf_random = RandomizedSearchCV(estimator=rf, param_distributions=random_grid, n_iter=100,
                                   cv=inner_cv, verbose=2, random_state=42,
                                   n_jobs=-1, scoring=my_squared_score)
    # Fit the random search model
    rf_random.fit(X_data[train_ids, :], y_data.iloc[train_ids])
    print(rf_random.best_params_)

    nested_cv_scores.append(rf_random.score(X_data[test_ids,:], y_data.iloc[test_ids]))

print("Nested cv score - meta learning: " + str(np.mean(nested_cv_scores)))

希望对您有帮助。

最好的问候,费利克斯

© www.soinside.com 2019 - 2024. All rights reserved.