train_test_split#

sklearn.model_selection.train_test_split(*arrays, test_size=None, train_size=None, random_state=None, shuffle=True, stratify=None)[源代码]#

将数组或矩阵拆分为随机训练和测试子集。

包装输入验证的快速实用程序, next(ShuffleSplit().split(X, y)) ,以及将数据输入到单个调用中的应用程序,以将数据拆分(以及可选地子采样)到一行代码中。

阅读更多的 User Guide .

参数:
*arrays具有相同长度/形状的索引序列 [0]

允许的输入是列表、numpy数组、scipy-sparse矩阵或pandas格式。

test_sizefloat或int,默认=无

如果为浮点数,则应介于0.0和1.0之间,表示要包含在测试拆分中的数据集的比例。如果为int,则表示测试样本的绝对数量。如果无,则该值设置为列车大小的补数。如果 train_size 也为“无”,则将其设置为0.25。

train_sizefloat或int,默认=无

如果是浮动的,则应介于0.0和1.0之间,并表示要包含在列车拆分中的数据集比例。如果是int,则表示火车样本的绝对数。如果无,该值将自动设置为测试大小的补数。

random_stateint,RandomState实例或无,默认=无

控制在应用拆分之前应用于数据的混洗。传递一个int值,以便在多个函数调用中获得可重复的输出。看到 Glossary .

shuffle布尔,默认=True

在拆分之前是否对数据进行洗牌。如果shuffle=False,那么分层必须为无。

stratify类数组,默认=无

如果不是无,则以分层方式拆分数据,并使用其作为类标签。阅读更多的 User Guide .

返回:
splitting列表,长度=2 * len(数组)

包含输入的训练测试拆分的列表。

Added in version 0.16: If the input is sparse, the output will be a scipy.sparse.csr_matrix. Else, output type is the same as the input type.

示例

>>> 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]]