sklearn的train_test_split方法

这个方法是对数据进行分开,一共四个返回值,分别是训练集的样本,训练集的目标值,测试集的样本,测试集的目标值,顺序就是这样子的。
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]]

暂存,不对的再改正。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章