函数名:train_test_split
    所在包:sklearn.model_selection
    功能:划分数据的训练集与测试集
    参数解读:train_test_split (*arrays,test_size, train_size, rondom_state=None, shuffle=True, stratify=None)

    • arrays:特征数据和标签数据(array,list,dataframe等类型),要求所有数据长度相同。
    • test_size / train_size: 测试集/训练集的大小,若输入小数表示比例,若输入整数表示数据个数。
    • rondom_state:随机种子(一个整数),其实就是一个划分标记,对于同一个数据集,如果rondom_state相同,则划分结果也相同。
    • shuffle:是否打乱数据的顺序,再划分,默认True。
    • stratify:none或者array/series类型的数据,表示按这列进行分层采样。

    举个栗子:

    1. 特征数据:data
    2. a b c
    3. 0 1 2 3
    4. 1 1 3 6
    5. 2 2 3 8
    6. 3 1 5 7
    7. 4 2 4 8
    8. 5 2 3 6
    9. 6 1 4 8
    10. 7 2 3 6
    11. 标签数据:label
    12. [2,3,5,6,8,0,2,3]
    13. #划分
    14. xtrain,xtest,ytrain,ytest=train_test_split(data,label,test_size=0.2,stratify=data['a'],random_state=1)
    15. 训练特征集:
    16. a b c
    17. 0 1 2 3
    18. 2 2 3 8
    19. 3 1 5 7
    20. 5 2 3 6
    21. 6 1 4 8
    22. 4 2 4 8
    23. 测试特征集:
    24. a b c
    25. 1 1 3 6
    26. 7 2 3 6
    27. 训练集与测试集按照a列来分层采样,且无论重复多少次上述语句,划分结果都相同。
    1. from __future__ import print_function
    2. import numpy as np
    3. from sklearn.model_selection import train_test_split
    4. X, y = np.arange(10).reshape((5, 2)), range(5)
    5. print(X)
    6. # [[ 0 1]
    7. # [ 2 3]
    8. # [ 4 5]
    9. # [ 6 7]
    10. # [ 8 9]]
    11. print(y)
    12. # range(0, 5), [0, 1, 2, 3, 4]
    13. X_train, X_test, y_train, y_test = train_test_split(X, y,
    14. test_size = 0.4, random_state = 22)
    15. print(X_train)
    16. # [[6 7]
    17. # [0 1]
    18. # [8 9]]
    19. print(y_train)
    20. # [3, 0, 4]
    21. print(X_test)
    22. # [[2 3]
    23. # [4 5]]
    24. print(y_test)
    25. # [1, 2]