sklearn的KFold,GroupKFold,StratifiedKFold区分

机器学习模型训练中对数据进行K折交叉训练是一个常见的策略,其中sklean库中的KFold,GroupKFold,StratifiedKFold就是实现对数据集K折划分的方法,这三个方法的区别总结如下。

KFold:是对数据集顺序按顺序K折划分;

GroupKFold:是按训练者自己的需求进行的自定义划分,比如定义需要某些类别在训练集上多点数据;

StratifiedKFold:则是分层采样,确保训练集,验证集中各类别样本的比例与原始数据集中相同;

这三种方法简单的代码示例:

import numpy as np
from sklearn.model_selection import KFold,GroupKFold,StratifiedKFold
X=np.array([[1,2],[3,4],[5,6],[7,8],[9,10],[11,12],[13,14],[15,16],[17,18],[19,20]])
y=np.array([1,1,1,1,2,2,2,3,3,3])

#KFold
print('KFlod:')
kf=KFold(n_splits=5)
for train_index,test_index in kf.split(X):
    print("Train Index:",train_index,",Test Index:",test_index)
    X_train,X_test=X[train_index],X[test_index]
    y_train,y_test=y[train_index],y[test_index]

# GroupKFold
print('GroupKFold:')
groups=np.array([1,1,1,1,2,2,2,3,3,3])
group_kfold=GroupKFold(n_splits=3)
for train_index,test_index in group_kfold.split(X,y,groups):
    print("Train Index:",train_index,",Test Index:",test_index)
    X_train,X_test=X[train_index],X[test_index]
    y_train,y_test=y[train_index],y[test_index]

# StratifiedKFold
print('StratifiedKFold:')
skf=StratifiedKFold(n_splits=3)
for train_index,test_index in skf.split(X,y):
    print("Train Index:",train_index,",Test Index:",test_index)
    X_train,X_test=X[train_index],X[test_index]
    y_train,y_test=y[train_index],y[test_index]


运行结果如下,打印了每次K折划分中数据集的index:

Train Index: [2 3 4 5 6 7 8 9] ,Test Index: [0 1]
Train Index: [0 1 4 5 6 7 8 9] ,Test Index: [2 3]
Train Index: [0 1 2 3 6 7 8 9] ,Test Index: [4 5]
Train Index: [0 1 2 3 4 5 8 9] ,Test Index: [6 7]
Train Index: [0 1 2 3 4 5 6 7] ,Test Index: [8 9]
GroupKFold:
Train Index: [4 5 6 7 8 9] ,Test Index: [0 1 2 3]
Train Index: [0 1 2 3 4 5 6] ,Test Index: [7 8 9]
Train Index: [0 1 2 3 7 8 9] ,Test Index: [4 5 6]
StratifiedKFold:
Train Index: [2 3 5 6 8 9] ,Test Index: [0 1 4 7]
Train Index: [0 1 3 4 6 7 9] ,Test Index: [2 5 8]
Train Index: [0 1 2 4 5 7 8] ,Test Index: [3 6 9]

Process finished with exit code 0

 

参考:https://www.cnblogs.com/nolonely/p/7007432.html

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Briwisdom

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值