2019-07-11 13:14:40 3462瀏覽
今天千鋒扣丁學(xué)堂Python培訓(xùn)老師給大家分享一篇關(guān)于Python實(shí)現(xiàn)K折交叉驗(yàn)證方法步驟的詳細(xì)介紹,首先在學(xué)習(xí)時(shí)測(cè)試集上的誤差我們通常稱作“泛化誤差”。要想得到“泛化誤差”首先得將數(shù)據(jù)集劃分為訓(xùn)練集和測(cè)試集。那么怎么劃分呢?常用的方法有兩種,k折交叉驗(yàn)證法和自助法。介紹這兩種方法的資料有很多。下面是k折交叉驗(yàn)證法的python實(shí)現(xiàn)。
##一個(gè)簡(jiǎn)單的2折交叉驗(yàn)證 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折交叉驗(yàn)證方法 查一下KFold函數(shù)的參數(shù) 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) #小結(jié):KFold這個(gè)包 劃分k折交叉驗(yàn)證的時(shí)候,是以TEST集的順序?yàn)橹鞯?,舉例來(lái)說(shuō),如果劃分4折交叉驗(yàn)證,那么TEST選取的順序?yàn)閇0].[1],[2],[3]。 #提升 import numpy as np from sklearn.model_selection import KFold #Sample=np.random.rand(50,15) #建立一個(gè)50行12列的隨機(jī)數(shù)組 Sam=np.array(np.random.randn(1000)) #1000個(gè)隨機(jī)數(shù) New_sam=KFold(n_splits=5) for train_index,test_index in New_sam.split(Sam): #對(duì)Sam數(shù)據(jù)建立5折交叉驗(yàn)證的劃分 #for test_index,train_index in New_sam.split(Sam): #默認(rèn)第一個(gè)參數(shù)是訓(xùn)練集,第二個(gè)參數(shù)是測(cè)試集 #print(train_index,test_index) Sam_train,Sam_test=Sam[train_index],Sam[test_index] print('訓(xùn)練集數(shù)量:',Sam_train.shape,'測(cè)試集數(shù)量:',Sam_test.shape) #結(jié)果表明每次劃分的數(shù)量 #Stratified k-fold 按照百分比劃分?jǐn)?shù)據(jù) 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 按照百分比劃分?jǐn)?shù)據(jù) 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個(gè)隨機(jī)數(shù) m1=np.append(m,y3) n=[i//10 for i in range(30)] #生成25個(gè)重復(fù)數(shù)據(jù) 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]
【關(guān)注微信公眾號(hào)獲取更多學(xué)習(xí)資料】 【掃碼進(jìn)入Python全棧開發(fā)免費(fèi)公開課】
查看更多關(guān)于"Python開發(fā)資訊"的相關(guān)文章>