【问题标题】:How to retrieve the random_state of sklearn.model_selection.train_test_split?如何检索 sklearn.model_selection.train_test_split 的 random_state?
【发布时间】:2021-02-09 07:27:33
【问题描述】:

如何检索sklearn.model_selection.train_test_split的随机状态?

在不设置random_state 的情况下,我使用train_test_split 拆分我的数据集。因为在拆分数据集上训练的机器学习模型表现非常好,所以我想检索用于拆分数据集的random_state。有没有类似numpy.random.get_state()

【问题讨论】:

    标签: python python-3.x scikit-learn


    【解决方案1】:

    什么意思?

    如果你想知道你使用的是哪个random_state,你必须在运行函数时使用random_state,例如:

    X_train, X_test, y_train, y_test = train_test_split(
    ...     X, y, test_size=0.33, random_state=42)
    

    默认设置为none,参见docs

    这里还有informationrandom_state

    或者你的意思是this

    【讨论】:

    • 谢谢你的回答,我的意思是我在没有设置random_state的情况下将我的数据集与train_test_split分开,我可以检索train_test_split之后使用的random_state吗?
    【解决方案2】:

    如果你跟踪train_test_split的调用栈,你会发现random_state参数是这样使用的:

    from sklearn.utils import check_random_state
    rng = check_random_state(self.random_state)
    print(rng)
    

    check_random_state的相关部分是

    def check_random_state(seed):
        if seed is None or seed is np.random:
            return np.random.mtrand._rand
    

    如果random_state=None,你会得到默认的numpy.random.RandomState单例,你可以用它来生成新的随机数,例如:

    print(rng.permutation(10))
    print(rng.randn(10))
    

    有关更多信息,请参阅这些问题:

    【讨论】:

    • 那么在这种情况下我将如何使用它:kf = KFold(n_splits = 10, shuffle = True, random_state = None) rng = check_random_state(self.random_state) 因为这给了我以下错误:NameError: name 'self' is not defined
    猜你喜欢
    • 2020-08-21
    • 2023-03-07
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 2021-03-30
    • 2020-09-27
    • 2019-03-25
    • 2019-04-14
    相关资源
    最近更新 更多