18

我正在看这个教程:https ://www.dataquest.io/mission/74/getting-started-with-kaggle

我到了第 9 部分,做出预测。其中有一些数据称为泰坦尼克号,然后使用以下方法将其分成折叠:

# Generate cross validation folds for the titanic dataset.  It return the row indices corresponding to train and test.
# We set random_state to ensure we get the same splits every time we run this.
kf = KFold(titanic.shape[0], n_folds=3, random_state=1)

我不确定它到底在做什么以及 kf 是什么类型的对象。我尝试阅读文档,但没有太大帮助。另外,一共有三折(n_folds=3),为什么后面只能在这一行访问train和test(我怎么知道他们叫train和test)?

for train, test in kf:
4

3 回答 3

29

KFold 将提供训练/测试索引来分割训练和测试集中的数据。它将数据集拆分为k连续的折叠(默认情况下不打乱)。然后每个折叠使用一次验证集,而k - 1剩余的折叠形成训练集(source)。

假设您有一些从 1 到 10 的数据索引。如果您使用n_fold=k,在第一次迭代中,您将获得i第 'th(i<=k)折作为测试索引,剩余的(k-1)折(没有i第 'th 折)一起作为训练索引。

一个例子

import numpy as np
from sklearn.cross_validation import KFold

x = [1,2,3,4,5,6,7,8,9,10,11,12]
kf = KFold(12, n_folds=3)

for train_index, test_index in kf:
    print (train_index, test_index)

输出

折叠 1:[ 4 5 6 7 8 9 10 11] [0 1 2 3]

折叠 2: [ 0 1 2 3 8 9 10 11] [4 5 6 7]

折叠 3:[0 1 2 3 4 5 6 7] [8 9 10 11]

sklearn 0.20 的导入更新:

KFold 对象在 0.20 版本中移至sklearn.model_selection模块。要在 sklearn 0.20+ 中导入 KFold,请使用from sklearn.model_selection import KFold. KFold 当前文档来源

于 2016-03-17T14:22:50.883 回答
1

分享我目前学到的关于 KF 的理论信息。

KFOLD 是一种模型验证技术,它不使用您的预训练模型。相反,它只是使用超参数并使用 k-1 个数据集训练一个新模型,并在第 k 个数据集上测试相同的模型。

K 个不同的模型仅用于验证。

它将返回基于第 k 个测试数据集的 K 个不同的分数(准确率百分比)。而我们一般取平均值来分析模型。

我们对要分析的所有不同模型重复此过程。简要算法:

  1. 将数据拆分为训练和测试部分。
  2. 在这个训练数据上训练了不同的模型,比如 SVM、RF、LR。
   2.a Take whole data set and divide in to K-Folds.
   2.b Create a new model with the hyper parameter received after training on step 1.
   2.c Fit the newly created model on K-1 data set.
   2.d Test on Kth data set
   2.e Take average score.
  1. 分析不同的平均分,从 SVM、RF 和 LR 中选出最好的模型。

这样做的原因很简单,我们通常存在数据缺陷,如果我们将整个数据集划分为:

  1. 训练
  2. 验证
  3. 测试

我们可能会遗漏相对较小的数据块,这可能会过度拟合我们的模型。也有可能一些数据在我们的训练中保持不变,我们没有针对这些数据分析行为。

KF 克服了这两个问题。

于 2019-05-09T04:59:43.200 回答
0

该过程有一个称为 k 的参数,它指的是给定数据样本将被分成的组数。因此,该过程通常称为 k 折交叉验证。When a specific value for k is chosen, it may be used in place of k in the reference to the model, such as k=10 becoming 10-fold cross-validation..

您可以参考这篇文章了解更多信息。 https://medium.com/@xzz201920/stratifiedkfold-vs-kfold-vs-stratifiedshufflesplit-ffcae5bfdf

于 2020-04-29T14:47:02.417 回答