Python实现K折交叉验证法的方法步骤

yipeiwu_com5年前Python基础

学习器在测试集上的误差我们通常称作“泛化误差”。要想得到“泛化误差”首先得将数据集划分为训练集和测试集。那么怎么划分呢?常用的方法有两种,k折交叉验证法和自助法。介绍这两种方法的资料有很多。下面是k折交叉验证法的python实现。

##一个简单的2折交叉验证
from sklearn.model_selection import KFold
import numpy as np
X=np.array([[1,2],[3,4],[1,3],[3,5]])
Y=np.array([1,2,3,4])
KF=KFold(n_splits=2) #建立4折交叉验证方法 查一下KFold函数的参数
for train_index,test_index in KF.split(X):
  print("TRAIN:",train_index,"TEST:",test_index)
  X_train,X_test=X[train_index],X[test_index]
  Y_train,Y_test=Y[train_index],Y[test_index]
  print(X_train,X_test)
  print(Y_train,Y_test)
#小结:KFold这个包 划分k折交叉验证的时候,是以TEST集的顺序为主的,举例来说,如果划分4折交叉验证,那么TEST选取的顺序为[0].[1],[2],[3]。

#提升
import numpy as np
from sklearn.model_selection import KFold
#Sample=np.random.rand(50,15) #建立一个50行12列的随机数组
Sam=np.array(np.random.randn(1000)) #1000个随机数
New_sam=KFold(n_splits=5)
for train_index,test_index in New_sam.split(Sam): #对Sam数据建立5折交叉验证的划分
#for test_index,train_index in New_sam.split(Sam): #默认第一个参数是训练集,第二个参数是测试集
  #print(train_index,test_index)
  Sam_train,Sam_test=Sam[train_index],Sam[test_index]
  print('训练集数量:',Sam_train.shape,'测试集数量:',Sam_test.shape) #结果表明每次划分的数量


#Stratified k-fold 按照百分比划分数据
from sklearn.model_selection import StratifiedKFold
import numpy as np
m=np.array([[1,2],[3,5],[2,4],[5,7],[3,4],[2,7]])
n=np.array([0,0,0,1,1,1])
skf=StratifiedKFold(n_splits=3)
for train_index,test_index in skf.split(m,n):
  print("train",train_index,"test",test_index)
  x_train,x_test=m[train_index],m[test_index]
#Stratified k-fold 按照百分比划分数据
from sklearn.model_selection import StratifiedKFold
import numpy as np
y1=np.array(range(10))
y2=np.array(range(20,30))
y3=np.array(np.random.randn(10))
m=np.append(y1,y2) #生成1000个随机数
m1=np.append(m,y3)
n=[i//10 for i in range(30)] #生成25个重复数据

skf=StratifiedKFold(n_splits=5)
for train_index,test_index in skf.split(m1,n):
  print("train",train_index,"test",test_index)
  x_train,x_test=m1[train_index],m1[test_index]

Python中貌似没有自助法(Bootstrap)现成的包,可能是因为自助法原理不难,所以自主实现难度不大。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

让python同时兼容python2和python3的8个技巧分享

python邮件列表里有人发表言论说“python3在10内都无法普及”。在我看来这样的观点有些过于悲观,python3和python2虽然不兼容,但他们之间差别并没很多人想像的那么大。...

Python打包可执行文件的方法详解

本文实例讲述了Python打包可执行文件的方法。分享给大家供大家参考,具体如下: Python程序需要依赖本机安装的Python库,若想在没有安装Python的机器上运行,则需要打包分发...

详解Python编程中包的概念与管理

Python中的包 包是一个分层次的文件目录结构,它定义了一个由模块及子包,和子包下的子包等组成的Python的应用环境。 考虑一个在Phone目录下的pots.py文件。这个文件有如下...

快速排序的四种python实现(推荐)

快速排序算法,简称快排,是最实用的排序算法,没有之一,各大语言标准库的排序函数也基本都是基于快排实现的。 本文用python语言介绍四种不同的快排实现。 1. 一行代码实现的简洁版本...

python打包生成的exe文件运行时提示缺少模块的解决方法

python打包生成的exe文件运行时提示缺少模块的解决方法

事情是这样的我用打包命令:pyinstaller -F E:\python\clpicdownload\mypython.py打包了一个exe程序,但是运行时提示我缺 少bs4模块然后我...