使用sklearn中的函數可以很方便的將數據划分為trainset 和 testset
該函數為sklearn.cross_validation.train_test_split,用法如下:
>>> import numpy as np >>> from sklearn.cross_validation 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]
其中 test_size是樣本占比,如果是整數的話就是樣本的數量;
random_state是隨機數的種子,不同的種子會造成不同的隨機采樣結果,相同的種子采樣結果相同。
參考: