python中写一个10折交叉验证
文章目录前言总结前言今天用python需要一个10折交叉验证,我当时是手动划分我首先设置随机数种子,然后我原始的数据是有x个nnn的矩阵然后我然后把x随机划分成10份按照从0:0.1x作为test,0.1x到最后作为train从0.1x到0.2x作为test,0到0.1x和0.2x到最后这两部分作为train…………一直到0.9x到最后作为test,0到0.9x作为train后来发现python有
·
前言
今天用python需要一个10折交叉验证,我当时是手动划分
我首先设置随机数种子,然后我原始的数据是有x个nnn的矩阵
然后我然后把x随机划分成10份
按照从0:0.1x作为test,0.1x到最后作为train
从0.1x到0.2x作为test,0到0.1x和0.2x到最后这两部分作为train
……
……
一直到0.9x到最后作为test,0到0.9x作为train
后来发现python有写好的KFold,有了这个我发现省事多了,我就换了个处理方法
from sklearn.model_selection import KFold
def Split_Sets_10_Fold(total_fold, data):
#total_fold是你设定的几折,我这里之后带实参带10就行,data就是我需要划分的数据
#train_index,test_index用来存储train和test的index(索引)
train_index = []
test_index = []
kf = KFold(n_splits=total_fold, shuffle=True, random_state=True)
#这里设置shuffle设置为ture就是打乱顺序在分配
for train_i, test_i in kf.split(data):
train_index.append(train_i)
test_index.append(test_i)
return train_index, test_index
之后调用该函数
total_fold = 10
[train_index, test_index] = Split_Sets_10_Fold(total_fold, data)
train_data = data[train_index, :, :, :] #得到训练数据
test_data = data[test_index, :,:,:] #得到测试数据
总结
发现自己的不好才能找到更好的,加油
更多推荐
已为社区贡献2条内容
所有评论(0)