有没有办法在 GridSearchCV 中查看交叉验证的折叠?

Is there a way to see the folds for cross-validation in GridSearchCV?

我目前正在 Python 中使用 GridSearchCV 进行 3 倍 cv 优化超参数。我只是想知道是否有任何方法可以查看 GridSearchCV 中使用的 cv 中训练和测试数据的索引?

如果您不想在 CV-stage 期间折叠之前打乱样本,则可以这样做。您可以将 KFold(或另一个 CV-class)的实例传递给 GridSearchCV 构造函数并像这样访问它的折叠:

import pandas as pd
import numpy as np
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold

params = {'penalty' : ['l1', 'l2'], 'C' : [1,2,3]}
grid = GridSearchCV(LogisticRegression(), params, cv=KFold(n_splits=3))

X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [5, 6], [7, 8]])

for train, test in grid.cv.split(X):
    print('TRAIN: ', train, ' TEST: ', test)

打印:

TRAIN:  [2 3 4 5]  TEST:  [0 1]
TRAIN:  [0 1 4 5]  TEST:  [2 3]
TRAIN:  [0 1 2 3]  TEST:  [4 5]

对于 non-shuffled CV,折叠始终相同,因此您可以确定这些是在 grid-search 期间使用的折叠。

如果你想在折叠之前打乱样本,那就有点复杂了,因为每次调用 cv.split() 都会产生不同的拆分。我可以想到两种方法:

  1. 您可以为 CV-object 提供一个固定的 random_state,例如KFold(n_splits=3, shuffle=True, random_state=42).

  2. 在创建 GridSearchCV 对象之前,从 KFold 迭代器创建一个列表。

因此,对于第二种方法,执行:

grid = GridSearchCV(LogisticRegression(), params, 
                    cv=list(KFold(n_splits=3, shuffle=True).split(X)))

除迭代器外,列表是固定对象,除非您手动操作它,否则它将在所有 GridSearch 迭代中保持相同的值。