Python 之 sklearn 交叉验证 数据拆分

http://blog.csdn.net/u013630349/article/details/47133283


本文K折验证拟采用的是 Python 中 sklearn 包中的 StratifiedKFold 方法。

方法思想详见:http://scikit-learn.org/stable/modules/cross_validation.html

StratifiedKFold is a variation of k-fold which returns stratified folds: each set contains approximately the same percentage of samples of each target class as the complete set.

【译】

StratifiedKFold 是一种将数据集中每一类样本的数据成分,按均等方式拆分的方法。

其它划分方法详见:http://scikit-learn.org/stable/modules/cross_validation.html

闲言少叙,直接上代码。

【屌丝源码】

[python]  view plain  copy
  1. import numpy  
  2. import h5py  
  3. import sklearn  
  4. from sklearn import cluster,cross_validation  
  5. from sklearn.cluster import AgglomerativeClustering  
  6. from sklearn.cross_validation import StratifiedKFold  
  7.   
  8. ## 生成一个随机矩阵并保存  
  9. #arr = numpy.random.random([200,400])  
  10. #labvec = []  
  11. #for i in numpy.arange(0,200):  
  12. #    j = i%10  
  13. #    arr[i,j*20:j*20+20] = arr[i,j*20:j*20+20]+10  
  14. #    labvec.append(j)  
  15. #arr = arr.T  
  16. #file = h5py.File('arr.mat','w')      
  17. #file.create_dataset('arr', data = arr)  
  18. #file.close()  
  19. #file = h5py.File('labvec.mat','w')      
  20. #file.create_dataset('labvec', data = labvec)  
  21. #file.close()  
  22. # 读方式打开文件  
  23. myfile=h5py.File('arr.mat','r')  
  24. arr = myfile['arr'][:]  
  25. myfile.close()  
  26. arr = arr.T  
  27. myfile=h5py.File('labvec.mat','r')  
  28. labvec = myfile['labvec'][:]  
  29. myfile.close()  
  30. skf = StratifiedKFold(labvec, 4)  
  31. train_set = []  
  32. test_set = []  
  33. for train, test in skf:  
  34.     train_set.append(train)  
  35.     test_set.append(test)  


详见: http://scikit-learn.org/stable/modules/cross_validation.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值