train_test_split()函数是用来随机划分样本数据为训练集和测试集的,当然也可以人为的切片划分。
优点:随机客观的划分数据,减少人为因素
完整模板:
train_X,test_X,train_y,test_y = train_test_split(train_data,train_target,test_size=0.3,random_state=5)
参数解释:
train_data:待划分样本数据
train_target:待划分样本数据的结果(标签)
test_size:测试数据占样本数据的比例,若整数则样本数量
random_state:设置随机数种子,保证每次都是同一个随机数。若为0或不填,则每次得到数据都不一样
In [11]: from sklearn.model_selection import train_test_split In [12]: import numpy as np In [13]: X,y = np.arange(12).reshape(6,2),np.arange(6) In [14]: X Out[14]: array([[ 0, 1], [ 2, 3], [ 4, 5], [ 6, 7], [ 8, 9], [10, 11]]) In [15]: y Out[15]: array([0, 1, 2, 3, 4, 5]) In [16]: train_X,test_X,train_y,test_y = train_test_split(X,y,test_size=0.3,random_state= ...: 17) In [17]: train_X Out[17]: array([[ 8, 9], [ 0, 1], [10, 11], [ 2, 3]]) In [18]: train_y Out[18]: array([4, 0, 5, 1]) In [19]: test_X Out[19]: array([[4, 5], [6, 7]]) In [20]: test_y Out[20]: array([2, 3])
随机产生样本:
from sklearn.datasets import make_classification X, y = make_classification( #x 对应数据,y 对应标签(就是数据原本数字型的标签 或者 字符串的标签转换为数字型的标签) n_samples=2000, #样本点 n_features=20, #特征维数 100个 特征 n_classes=2, #二维识别,二分类 random_state=17) #随机种子,每次随机数都一样 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, #70%是训练集,30%测试集 random_state=17) #一样的随机种子
利用sklearn的make_classification来随机产生一组样本数据,再用train_test_split来划分