Scikit-learn,GroupKFold与洗牌组合?

gug*_*n1c 8 python shuffle scikit-learn cross-validation

我正在使用来自scikit-learn的StratifiedKFold,但现在我还要注意"团体".有很好的功能GroupKFold,但我的数据非常依赖于时间.与帮助中的相似,即周数是分组索引.但每周应该只有一个折叠.

假设我需要10倍.在我可以使用GroupKFold之前,我需要先将数据混洗.

洗牌是小组的 - 所以整个小组应该互相洗牌.

有办法做的是scikit - 以某种方式学习优雅吗?在我看来,GroupKFold首先可以自动调整数据.

如果没有办法用scikit做,有人可以写一些有效的代码吗?我有大量的数据集.

矩阵,标签,组作为输入

Mel*_*ssa 8

我认为使用sklearn.utils.shuffle是一个优雅的解决方案!

对于X,Y和组中的数据:

from sklearn.utils import shuffle
X_shuffled, y_shuffled, groups_shuffled = shuffle(X, y, groups, random_state=0)
Run Code Online (Sandbox Code Playgroud)

然后使用X_shuffled,y_shuffled和groups_shuffled与GroupKFold:

from sklearn.model_selection import GroupKFold
group_k_fold = GroupKFold(n_splits=10)
splits = group_k_fold.split(X_shuffled, y_shuffled, groups_shuffled)
Run Code Online (Sandbox Code Playgroud)

当然,您可能希望多次洗牌并对每次shuffle进行交叉验证.你可以把整个东西放在一个循环中 - 这是一个完整的例子,有5个shuffle(只有3个分裂而不是你需要的10个):

X = np.arange(20).reshape((10, 2))
y = np.arange(10)
groups = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7]

n_shuffles = 5
group_k_fold = GroupKFold(n_splits=3)

for i in range(n_shuffles):
    X_shuffled, y_shuffled, groups_shuffled = shuffle(X, y, groups, random_state=i)
    splits = group_k_fold.split(X_shuffled, y_shuffled, groups_shuffled)
    # do something with splits here, I'm just printing them out
    print 'Shuffle', i
    print 'groups_shuffled:', groups_shuffled
    for train_idx, val_idx in splits:
        print 'Train:', train_idx
        print 'Val:', val_idx
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这种策略似乎行不通。参见 /sf/ask/2930172941/,其中显示它只是重新排列每个折叠的元素,但它没有给出新的分割! (3认同)