【问题标题】:Why random_state differs in test_train_split of Scikit Learn [duplicate]为什么 Scikit Learn 的 test_train_split 中的 random_state 不同 [重复]
【发布时间】:2021-07-15 02:34:21
【问题描述】:

我一直在使用 Scikit learn 编写一些用于信用卡欺诈检测问题的代码。 我使用 train_test_split 将数据拆分为训练、测试和验证数据集。

x_train,x_test,y_train,y_test=train_test_split(x,y,train_size=0.7,random_state=123)

我不明白为什么这里的 random_state 是 123 同时在训练和测试数据集之间分割数据和

part_x_train, x_val, part_y_train, y_val = train_test_split(x_train, y_train, test_size=0.2, random_state=2)

这里 random_state 为 2,同时在训练和验证数据集之间拆分数据。为什么差别这么大? 我一直在尝试使用不同的 random_states,但无法找出区别。

【问题讨论】:

  • 你读过the docs这个函数吗?使用该参数的原因在此处定义:“在应用拆分之前控制应用于数据的改组。传递一个 int 以实现跨多个函数调用的可重现输出。” (强调)读完之后,您的具体问题是什么?

标签: python machine-learning scikit-learn train-test-split


【解决方案1】:

train_test_split 函数将原始数据的行打乱,然后按比例制作训练数据集,其余用于测试。

因此,如果train_size = 0.7,该函数将对您的数据进行混洗,并保存 70% 的混洗数据用于训练和 30% 的测试。

如果您在没有声明随机状态的情况下运行train_test_split(x, y, train_size=0.7),则生成的拆分将(几乎)总是不同的。

我们设置随机状态的原因是告诉函数每次都以相同的方式打乱数据,以使我们的结果可复制。

换句话说,如果你运行train_test_split(x, y, train_size=0.7, random_state=123),你总是会得到相同的结果。

至于您的代码,请注意,您要拆分的数据在第二行也发生了变化。这是您的 cmets 代码:

# Divide `x` and `y` in 70% train and 30% test
#    Note that you are splitting `x` and `y`        ▼  ▼
x_train, x_test, y_train, y_test = train_test_split(x, y,
                                                    train_size=0.7,
                                                    random_state=123)

# Split the 70% into 80% train and 20% validation
#    Note that you are not splitting `x` and `y` anymore      ▼        ▼
part_x_train, x_val, part_y_train, y_val = train_test_split(x_train, y_train,
                                                            test_size=0.2,
                                                            random_state=2)

请注意,在第二次拆分中,您将拆分 x_trainy_train

这意味着您的代码需要 70% 的原始数据来创建训练数据集,然后将该新子集拆分为 80% 用于训练和 20% 用于验证。

【讨论】:

    猜你喜欢
    • 2017-09-05
    • 2014-05-15
    • 2020-12-14
    • 2017-01-02
    • 2018-10-11
    • 2019-01-12
    • 2017-06-17
    • 2017-02-25
    • 2018-08-21
    相关资源
    最近更新 更多