python 劃分資料集為訓練集和測試集
sklearn的cross_validation包中含有將資料集按照一定的比例,隨機劃分為訓練集和測試集的函式train_test_split
from sklearn.cross_validation import train_test_split
#x為資料集的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對應的是x,y中被抽取到的序號。
若train_test_split傳入的是帶有label的資料,則如下程式碼:
from sklearn.cross_validation import train_test_split
#dat為資料集,含有feature和label.
train, test = train_test_split(dat, test_size = 0.3)
train,test含有feature和label的。
自己寫了一個函式:
#X:含label的資料集:分割成訓練集和測試集
#test_size:測試集佔整個資料集的比例
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是抽取的資料集X的序號
train=X.ix[train_index]
test=X.ix[test_index]
return train,test