sklearn.model_selection中train_test_split的坑

无论是做机器学习还是深度学习,有个叫做数据集的东西不可忽视,有时候数据集的好坏会影响最后学习的效果。特别是没有现成处理好的数据集时需要我们自己动手搜集整理得到训练和测试的数据集。
我在处理数据集的时候喜欢把数据放在一个列表,label放在一个一个列表,然后利用sklearn.model_selection中的train_test_split函数来分割得到训练集和数据集。该函数的具体返回值和用法如下:

train_x,test_x,train_y,test_y = train_test_split(datas,labels,test_size=0.3,random_state=42)

datas:为数据集
labels:为数据集对应的分类
test_size:测试集占所有数据的比例
random_state:具体作用暂时未知(我踩的坑可能和它有关,后面写代码测试一下)

from sklearn.model_selection import train_test_split
import numpy as np
class0 = ['a','b','c','d','e']
label_0 = np.zeros(len(class0))
class1 = ['1','2','3','4','5']
label_1 = np.ones(len(class1))

datas = np.hstack((class0,class1))
labels = np.hstack((label_0,label_1))

#这是我的用法
train_x,test_x,train_y,test_y = train_test_split(datas,labels,test_size=0.3)
print(train_x)
print(test_x)
print(train_y)
print(test_y)

#测试一下参数random_state=42
train_x,test_x,train_y,test_y = train_test_split(datas,labels,test_size=0.3,random_state=2)
print(train_x)
print(test_x)
print(train_y)
print(test_y)

通过代码测试,我踩的坑果然和random_state这个参数有关,当忽略这个参数时每次运行得到两个分组都是随机的,每次可能都不一样,当设置random_state之后多次运行的分组结果相同。在网上看都让random_state=42,具体不知为啥,有兴趣可以探究一下,我把它设为2得到的结果也不发生变化。

作为一个严谨的我怎么能容忍不知道这个random_state是为啥呢?所以我就去查了一下。
当random_state=1,会生成一组随机数
当random_state=2, 会生成另一组随机数
。。。
这个是一一对应的,random_state=1,就固定得到那组随机数。

猜你喜欢

转载自blog.csdn.net/qq_25105061/article/details/108009963