【问题标题】:next() always gives the same index with a KFold generatornext() 总是给出与 KFold 生成器相同的索引
【发布时间】:2019-12-15 07:51:44
【问题描述】:

我正在关注此thread 以使用 sklean 的 KFold 生成用于交叉验证的 kfold 索引。

from sklearn.model_selection import KFold
import numpy as np

X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]])
y = np.array([1, 2, 3, 4, 5])

当我使用 for 循环时,一切正常:

for train_index, test_index in kf.split(X):
    print("TRAIN:", train_index, "TEST:", test_index)

给我:

TRAIN: [1 2 3 4] TEST: [0]
TRAIN: [0 2 3 4] TEST: [1]
TRAIN: [0 1 3 4] TEST: [2]
TRAIN: [0 1 2 4] TEST: [3]
TRAIN: [0 1 2 3] TEST: [4]

但是,当我使用next() 时,无论运行多少次,我总是得到相同的索引:

train_idx, test_idx = next(kf.split(X))
print(train_idx, test_idx)

[1 2 3 4] [0]

我有什么遗漏吗?谢谢

【问题讨论】:

  • 因为你一直打电话给.split然后 next。您需要在 .split 返回的内容上继续调用 next

标签: python scikit-learn


【解决方案1】:

如 cmets 中所述,您需要调用 next() 以获取 split() 返回的内容。

要尝试的代码:

from sklearn.model_selection import KFold
import numpy as np

X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]])
y = np.array([1, 2, 3, 4, 5])

kf = KFold(n_splits=5)

randomIter = kf.split(X)
train_idx, test_idx = next(randomIter)
print(train_idx, test_idx)
train_idx, test_idx = next(randomIter)
print(train_idx, test_idx)
train_idx, test_idx = next(randomIter)
print(train_idx, test_idx)
train_idx, test_idx = next(randomIter)
print(train_idx, test_idx)

【讨论】:

    猜你喜欢
    • 2016-04-28
    • 2018-02-11
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    相关资源
    最近更新 更多