转自:https://www..com/zhanglianbo/p/5701009.html
使用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是随机数的种子,不同的种子会造成不同的随机采样结果,相同的种子采样结果相同。
参考:
http://blog.sina.com.cn/s/blog_6a90ae320101a5rc.html
http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.train_test_split.html