K折交叉驗證法的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)現成的包,可能是因為自助法原理不難,所以自主實現難度不大。

 

下面推薦一篇Bootstrap的文章

http://blog.csdn.net/mrlevo520/article/details/53189615

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM