我正在阅读这篇关于如何为非常不平衡的数据集进行正确 KFold 的文章。在最后一个示例中,它展示了如何将数据集拆分为 2 折,50/50 训练/测试。一切都非常酷和有趣。然而,我想知道如何进行拆分,我还可以控制每个折叠中的类分布,例如 50/50 class0/class1(又名欠采样/过采样)。因此,鉴于以下数据,假设我想要 4 折,我正在寻找以下结果:
>Train: 0=8, 1=8,
>Train: 0=8, 1=8,
>Train: 0=8, 1=8,
>Train: 0=8, 1=8,
有没有办法用任何方法来实现这一点sklearn.model_selection
?我到处寻找这个没有运气。这可能是因为这种方法不应该与 KFold 一起使用吗?
# example of stratified train/test split with an imbalanced dataset
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
# generate 2 class dataset
X, y = make_classification(n_samples=1000, n_classes=2, weights=[0.99, 0.01], flip_y=0, random_state=1)
# split into train/test sets with same class ratio
trainX, testX, trainy, testy = train_test_split(X, y, test_size=0.5, random_state=2, stratify=y)
# summarize
train_0, train_1 = len(trainy[trainy==0]), len(trainy[trainy==1])
test_0, test_1 = len(testy[testy==0]), len(testy[testy==1])
print('>Train: 0=%d, 1=%d, Test: 0=%d, 1=%d' % (train_0, train_1, test_0, test_1))
>Train: 0=495, 1=5, Test: 0=495, 1=5