scikit-learn中的StratifiedKFold与KFold有何区别?

27

我使用这段代码来测试KFoldStratifiedKFold

import numpy as np
from sklearn.model_selection import KFold,StratifiedKFold

X = np.array([
    [1,2,3,4],
    [11,12,13,14],
    [21,22,23,24],
    [31,32,33,34],
    [41,42,43,44],
    [51,52,53,54],
    [61,62,63,64],
    [71,72,73,74]
])

y = np.array([0,0,0,0,1,1,1,1])

sfolder = StratifiedKFold(n_splits=4,random_state=0,shuffle=False)
floder = KFold(n_splits=4,random_state=0,shuffle=False)

for train, test in sfolder.split(X,y):
    print('Train: %s | test: %s' % (train, test))
print("StratifiedKFold done")

for train, test in floder.split(X,y):
    print('Train: %s | test: %s' % (train, test))
print("KFold done")

我发现StratifiedKFold可以保持标签的比例,但是KFold不能。

Train: [1 2 3 5 6 7] | test: [0 4]
Train: [0 2 3 4 6 7] | test: [1 5]
Train: [0 1 3 4 5 7] | test: [2 6]
Train: [0 1 2 4 5 6] | test: [3 7]
StratifiedKFold done
Train: [2 3 4 5 6 7] | test: [0 1]
Train: [0 1 4 5 6 7] | test: [2 3]
Train: [0 1 2 3 6 7] | test: [4 5]
Train: [0 1 2 3 4 5] | test: [6 7]
KFold done

看起来 StratifiedKFold 更好,那么 KFold 不应该被使用吗?

什么时候应该使用 KFold 而不是 StratifiedKFold


3
在那里有很棒的答案(如果你想深入了解StratifiedShuffleSplit除了StratifiedKFoldKFold)。 - amiola
3个回答

50

我认为你应该问:“何时使用StratifiedKFold而不是KFold?”

首先,您需要知道“KFold”和“Stratified”是什么。

KFold是一种交叉验证器,将数据集分成k个折叠。

Stratified旨在确保每个数据集折叠中具有给定标签的观测比例相同。

因此,这意味着StratifiedKFoldKFold的改进版本。

因此,这个问题的答案是:在处理具有不平衡类分布的分类任务时,我们应该优先选择StratifiedKFold而不是KFold


例如

假设有一个包含16个数据点和不平衡类分布的数据集。 在数据集中,12个数据点属于A类,其余(即4个)属于B类。 B类与A类的比率为1/3。 如果我们使用StratifiedKFold并设置k = 4,则在每个迭代中,训练集将包括来自A类的9个数据点和来自B类的3个数据点,而测试集包括来自A类的3个数据点和来自B类的1个数据点。

正如我们所看到的,StratifiedKFold通过保留数据集的类分布来拆分数据,而KFold则不考虑这一点。


你是不是想说“来自A类的4个数据点…”? - ABCD
KFold和Stratified KFold之间唯一的区别是每个Fold中类分布的平衡情况,你能确认吗? - Yacine Hajji
@SmallChess,请问为什么从A类中选取了4个数据点?请澄清一下。 - JayPeerachai

4
Assume Classification problem, Having 3 class(A,B,C) to predict.

Class  No_of_instance

 A           50 
 B           50
 C           50

**StratifiedKFold**

If data-set is  divided  into 5 fold. Then each fold will contains 10 instance from each class, i.e. no of instance per class is equal and follow  uniform distribution.

**KFold**

it will randomly took 30 instance and no of instance per class may or may not be equal or uniform.

**When to use**

Classification task use StratifiedKFold, and regression task use Kfold .
 
But if dataset contains  large number of instance, both StratifiedKFold and Kfold can be used in classification task.

1

StratifiedKFold:分层K折交叉验证 这个交叉验证对象是 KFold 的一个变种,它返回分层折叠。这些折叠是通过保留每个类别样本的百分比来生成的。

KFold:K折交叉验证 将数据集分成 k 个连续的折叠。

StratifiedKFold 用于在训练和测试中平衡每个类别的百分比。如果不需要,则使用KFOld


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接