模型训练中巧用CV

本文详细介绍了在机器学习中常用的交叉验证方法,包括分层KFold、KFold及如何使用Keras进行10折交叉验证。通过具体代码实例展示了不同交叉验证策略的实现方式,帮助读者深入理解并掌握交叉验证在实际项目中的应用。

1.分层KFold

import numpy as np
from sklearn.model_selection import StratifiedKFold
X=np.array([[1,2,3,4],
            [11,12,13,14],
            [21,22,23,24],
            [31,32,33,34],
            [41,42,43,44]
            ])
y=np.array([0,1,1,0,0])
folder=StratifiedKFold(n_splits=2,shuffle=False,random_state=1000)

for train_index,test_index in folder.split(X=X,y=y):
    print('训练集索引:',train_index,'测试集索引:',test_index)
    print('train:',X[train_index],'---',y[train_index])
    print('test:',X[test_index],'---',y[test_index])
print('*'*30)


训练集索引: [2 4] 测试集索引: [0 1 3]
train: [[21 22 23 24]
 [41 42 43 44]] --- [1 0]
test: [[ 1  2  3  4]
 [11 12 13 14]
 [31 32 33 34]] --- [0 1 0]
训练集索引: [0 1 3] 测试集索引: [2 4]
train: [[ 1  2  3  4]
 [11 12 13 14]
 [31 32 33 34]] --- [0 1 0]
test: [[21 22 23 24]
 [41 42 43 44]] --- [1 0]

2.KFold


from sklearn.model_selection import KFold
X=np.array([[1,2,3,4],
            [11,12,13,14],
            [21,22,23,24],
            [31,32,33,34],
            [41,42,43,44]
            ])
y=np.array([0,1,1,0,0])
folder=KFold(n_splits=2,shuffle=False,random_state=100)
for train_index,test_index in folder.split(X=X,y=y):
    print('训练集索引:',train_index,'测试集索引:',test_index)
    print('train:',X[train_index],'>>>',y[train_index])
    print('test:',X[test_index],'>>>',y[test_index])

训练集索引: [3 4] 测试集索引: [0 1 2]
train: [[31 32 33 34]
 [41 42 43 44]] >>> [0 0]
test: [[ 1  2  3  4]
 [11 12 13 14]
 [21 22 23 24]] >>> [0 1 1]
训练集索引: [0 1 2] 测试集索引: [3 4]
train: [[ 1  2  3  4]
 [11 12 13 14]
 [21 22 23 24]] >>> [0 1 1]
test: [[31 32 33 34]
 [41 42 43 44]] >>> [0 0]

3. 使用Keras进行10折交叉验证

for train,test in kfold.split(train_data_X,train_data_Y):
    model = getModel()
    t1,t2,t3,t4 = np.array(train_data_X)[train], np.array(train_data_X)[test],
np.array(train_data_Y)[train],np.array(train_data_Y)[test]
    train_D = data_generator(t1.tolist(), t3.tolist())
    dev_D = data_generator(t2.tolist(), t4.tolist())
    evaluator = Evaluate()
    model.fit_generator(train_D.__iter__(),
                        steps_per_epoch=len(train_D),
                        epochs=3,
                        callbacks=[evaluator,lrate]
                        )
    del model

K.clear_session()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值