學習器在測試集上的誤差我們通常稱作“泛化誤差”。要想得到“泛化誤差”首先得將數據集劃分為訓練集和測試集。那么怎么劃分呢?常用的方法有兩種,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)現成的包,可能是因為自助法原理不難,所以自主實現難度不大。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
