欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實現(xiàn)K折交叉驗證法的方法步驟

 更新時間:2019年07月11日 11:07:58   作者:榮一不是阿貝爾  
這篇文章主要介紹了Python實現(xiàn)K折交叉驗證法的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

學(xué)習(xí)器在測試集上的誤差我們通常稱作“泛化誤差”。要想得到“泛化誤差”首先得將數(shù)據(jù)集劃分為訓(xùn)練集和測試集。那么怎么劃分呢?常用的方法有兩種,k折交叉驗證法和自助法。介紹這兩種方法的資料有很多。下面是k折交叉驗證法的python實現(xiàn)。

##一個簡單的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函數(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這個包 劃分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列的隨機數(shù)組
Sam=np.array(np.random.randn(1000)) #1000個隨機數(shù)
New_sam=KFold(n_splits=5)
for train_index,test_index in New_sam.split(Sam): #對Sam數(shù)據(jù)建立5折交叉驗證的劃分
#for test_index,train_index in New_sam.split(Sam): #默認第一個參數(shù)是訓(xùn)練集,第二個參數(shù)是測試集
  #print(train_index,test_index)
  Sam_train,Sam_test=Sam[train_index],Sam[test_index]
  print('訓(xùn)練集數(shù)量:',Sam_train.shape,'測試集數(shù)量:',Sam_test.shape) #結(jié)果表明每次劃分的數(shù)量


#Stratified k-fold 按照百分比劃分數(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 按照百分比劃分數(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個隨機數(shù)
m1=np.append(m,y3)
n=[i//10 for i in range(30)] #生成25個重復(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]

Python中貌似沒有自助法(Bootstrap)現(xiàn)成的包,可能是因為自助法原理不難,所以自主實現(xiàn)難度不大。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論