這個方法是對數據進行分開,一共四個返回值,分別是訓練集的樣本,訓練集的目標值,測試集的樣本,測試集的目標值,順序就是這樣子的。
train_test_split中傳入的參數爲:數據集,目標集,測試集的大小其中測試集的大小是一個float類型。
下面用一個源碼中的小例子看一下:
>>> import numpy as np
>>> from sklearn.model_selection import train_test_split
>>> X, y = np.arange(10).reshape((5, 2)), range(5)
>>> X
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
>>> list(y)
[0, 1, 2, 3, 4]
>>> X_train, X_test, y_train, y_test = train_test_split(
... X, y, test_size=0.33, random_state=42)
...
>>> X_train
array([[4, 5],
[0, 1],
[6, 7]])
>>> y_train
[2, 0, 3]
>>> X_test
array([[2, 3],
[8, 9]])
>>> y_test
[1, 4]
>>> train_test_split(y, shuffle=False)
[[0, 1, 2], [3, 4]]
其中random_state表示隨機數種子,如果設置兩次一樣的隨機數種子,就能獲得完全一樣的數據集分開後的結果。
另外,源碼的小例子最後的測試只傳入了一個數據集:
train_test_split(y, shuffle=False)
shuffle:是對數據進行隨機排序,默認是True。
只傳入一個一維數據集時,數組長度小於5時會輸出最後一個爲目標集,否則爲最後兩個。
x, y = np.arange(10).reshape((5, 2)), range(8)
print(x)
y = list(y)
print(y)
print(train_test_split(y, shuffle=False))
輸出結果:
[[0 1]
[2 3]
[4 5]
[6 7]
[8 9]]
[0, 1, 2, 3, 4, 5, 6, 7]
[[0, 1, 2, 3, 4, 5], [6, 7]]
長度小於5:
y = range(4)
y = list(y)
print(train_test_split(y, shuffle=False))
結果:
[0, 1, 2, 3]
[[0, 1, 2], [3]]
暫存,不對的再改正。