【问题标题】:Why is stratifiedkfold generating the same splits in spite of using different random_state values?尽管使用不同的 random_state 值,为什么 stratifiedkfold 会生成相同的拆分?
【发布时间】:2018-12-07 18:23:36
【问题描述】:

我正在尝试使用 stratifiedkfold 拆分和 random_state 参数生成我的数据集的不同分层拆分。但是,当我使用不同的 random_state 值时,我仍然得到相同的拆分。我的理解是,通过使用不同的 random_state 值,您将能够生成不同的拆分。请让我知道我做错了什么。这是代码。

import numpy as np
X_train=np.ones(10)
Y_train=np.ones(10)

from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=5,random_state=0)
skf1 = StratifiedKFold(n_splits=5,random_state=100)


trn1=[]
cv1=[]
for train, cv in skf.split(X_train, Y_train):
    trn1=trn1+[train]
    cv1=cv1+[cv]

trn2=[]
cv2=[]
for train, cv in skf1.split(X_train, Y_train):
    trn2=trn2+[train]
    cv2=cv2+[cv]


for c in list(range(0,5)):
    print('Fold:'+str(c+1))
    print(trn1[c])
    print(trn2[c])
    print(cv1[c])
    print(cv2[c])

这是输出

Fold:1
[2 3 4 5 6 7 8 9]
[2 3 4 5 6 7 8 9]
[0 1]
[0 1]
Fold:2
[0 1 4 5 6 7 8 9]
[0 1 4 5 6 7 8 9]
[2 3]
[2 3]
Fold:3
[0 1 2 3 6 7 8 9]
[0 1 2 3 6 7 8 9]
[4 5]
[4 5]
Fold:4
[0 1 2 3 4 5 8 9]
[0 1 2 3 4 5 8 9]
[6 7]
[6 7]
Fold:5
[0 1 2 3 4 5 6 7]
[0 1 2 3 4 5 6 7]
[8 9]
[8 9]

【问题讨论】:

    标签: python-3.x random scikit-learn cross-validation


    【解决方案1】:

    如文档中所述:

    random_state : int,RandomState 实例或无,可选,默认=无

    如果是int,则random_state是随机数生成器使用的种子;如果是 RandomState 实例,则 random_state 是随机数生成器;如果没有,随机数生成器是 np.random 使用的 RandomState 实例。 在 shuffle == True 时使用

    因此,只需将 shuffle=True 添加到您的 StratifiedKFold 呼叫中即可。例如:

    skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
    skf1 = StratifiedKFold(n_splits=5, shuffle=True, random_state=100)
    

    输出:

    Fold:1
    [0 1 3 4 5 6 7 9]
    [0 1 2 3 4 5 8 9]
    [2 8]
    [6 7]
    Fold:2
    [0 1 2 3 5 6 7 8]
    [0 2 3 4 6 7 8 9]
    [4 9]
    [1 5]
    Fold:3
    [0 2 3 4 5 7 8 9]
    [0 1 3 5 6 7 8 9]
    [1 6]
    [2 4]
    Fold:4
    [0 1 2 4 5 6 8 9]
    [1 2 4 5 6 7 8 9]
    [3 7]
    [0 3]
    Fold:5
    [1 2 3 4 6 7 8 9]
    [0 1 2 3 4 5 6 7]
    [0 5]
    [8 9]
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 2022-01-04
    • 2012-06-07
    相关资源
    最近更新 更多