溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python 劃分?jǐn)?shù)據(jù)集為訓(xùn)練集和測(cè)試集的方法

發(fā)布時(shí)間:2020-08-23 10:22:03 來(lái)源:腳本之家 閱讀:844 作者:心雨心辰 欄目:開(kāi)發(fā)技術(shù)

sklearn的cross_validation包中含有將數(shù)據(jù)集按照一定的比例,隨機(jī)劃分為訓(xùn)練集和測(cè)試集的函數(shù)train_test_split

from sklearn.cross_validation import train_test_split
#x為數(shù)據(jù)集的feature熟悉,y為label.
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3)

得到的x_train,y_train(x_test,y_test)的index對(duì)應(yīng)的是x,y中被抽取到的序號(hào)。

若train_test_split傳入的是帶有l(wèi)abel的數(shù)據(jù),則如下代碼:

from sklearn.cross_validation import train_test_split
#dat為數(shù)據(jù)集,含有feature和label.
train, test = train_test_split(dat, test_size = 0.3)

train,test含有feature和label的。

自己寫了一個(gè)函數(shù):

#X:含label的數(shù)據(jù)集:分割成訓(xùn)練集和測(cè)試集
#test_size:測(cè)試集占整個(gè)數(shù)據(jù)集的比例
def trainTestSplit(X,test_size=0.3):
 X_num=X.shape[0]
 train_index=range(X_num)
 test_index=[]
 test_num=int(X_num*test_size)
 for i in range(test_num):
  randomIndex=int(np.random.uniform(0,len(train_index)))
  test_index.append(train_index[randomIndex])
  del train_index[randomIndex]
 #train,test的index是抽取的數(shù)據(jù)集X的序號(hào)
 train=X.ix[train_index] 
 test=X.ix[test_index]
 return train,test

以上這篇python 劃分?jǐn)?shù)據(jù)集為訓(xùn)練集和測(cè)試集的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI