python-3.x - 尽管使用不同的 random_state 值,为什么 stratifiedkfold 会生成相同的拆分?
问题描述
我正在尝试使用 stratifiedkfold split 和 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]
解决方案
如文档中所述:
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]
推荐阅读
- r - 我应该如何在 R 中有效地跨行格式化 gt 表?
- flutter - 在 ListView.builder 的末尾提供一些额外的空间
- python - 如何从表格行中抓取特定单词?
- amazon-web-services - 需要定期更新时使用 Dynamo 表的最佳实践
- python - 使用 matplotlib python 为数据透视表绘制折线图
- python - 向左旋转数组
- python - Pymongo - 快速搜索并留下重复项
- java - 自定义对象的 Spring GET 控制器集合
- python - 如何在 DataFrame 中添加具有来自另一个原始值的列
- javascript - 在 Promise Rejection (Typescript) 中返回未处理的错误