train_test_split()是sklearn.model_selection中的分离器函数

train_test_split()是sklearn.model_selection中的分离器函数,用于将数组或矩阵划分为训练集和测试集,函数样式为:
X_train, X_test, y_train, y_test = train_test_split(train_data, train_target, test_size, random_state,shuffle)

参数解释:

  • train_data:待划分的样本数据
  • train_target:待划分的对应样本数据的样本标签
  • test_size:1)浮点数,在0 ~ 1之间,表示样本占比(test_size = 0.3,则样本数据中有30%的数据作为测试数据,记入X_test,其余70%数据记入X_train,同时适用于样本标签);2)整数,表示样本数据中有多少数据记入X_test中,其余数据记入X_train
  • random_state:随机数种子,种子不同,每次采的样本不一样;种子相同,采的样本不变(random_state不取,采样数据不同,但random_state等于某个值,采样数据相同,取0的时候也相同,这可以自己编程尝试下,不过想改变数值也可以设置random_state = int(time.time()))
  • shuffle:洗牌模式,1)shuffle = False,不打乱样本数据顺序;2)shuffle = True,打乱样本数据顺序
    >>> import numpy as np
    >>> from sklearn.model_selection import train_test_split
    >>> X, y = np.arange(30).reshape((10, 3)), range(10)
    >>> X_train, X_test ,y_train, y_test= train_test_split(X, y,test_size=0.3, rando
    m_state = 20, shuffle=True)
    >>> X_train
    array([[15, 16, 17],
           [ 0,  1,  2],
           [ 6,  7,  8],
           [18, 19, 20],
           [27, 28, 29],
           [12, 13, 14],
           [ 9, 10, 11]])
    >>> X_test
    array([[21, 22, 23],
           [ 3,  4,  5],
           [24, 25, 26]])
    >>> y_train
    [5, 0, 2, 6, 9, 4, 3]
    >>> y_test
    [7, 1, 8]
    

    随机划分训练集和测试集train_test_split

    train_test_split是交叉验证中常用的函数,功能是从样本中随机的按比例选取train_data和test_data,形式为:

  • 
    from sklearn.model_selection import train_test_split
    
    #展示不同的调用方式
    
     
    
    train_set, test_set = train_test_split(data, test_size=0.2, random_state=42)
    
     
    
    #cross_validation代表交叉验证
    
    X_train,X_test, y_train, y_test =cross_validation.train_test_split(train_data,train_target,test_size=0.4, random_state=0)
    

    train_data:所要划分的样本特征集
    train_target:所要划分的样本结果
    test_size:样本占比,如果是整数的话就是样本的数量
    random_state:是随机数的种子。
    随机数种子:其实就是该组随机数的编号,在需要重复试验的时候,保证得到一组一样的随机数。比如你每次都填1,其他参数一样的情况下你得到的随机数组是一样的。但填0或不填,每次都会不一样。
    随机数的产生取决于种子,随机数和种子之间的关系遵从以下两个规则:
    种子不同,产生不同的随机数;种子相同,即使实例不同也产生相同的随机数。

猜你喜欢

转载自blog.csdn.net/dujuancao11/article/details/107661101
今日推荐