【问题标题】:Issue with Cross Validation交叉验证问题
【发布时间】:2017-08-27 18:06:49
【问题描述】:

我想使用留一出交叉验证。但我得到以下错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-19-f15f1e522706> in <module>()
      3 loo = LeaveOneOut(num_of_examples)
      4 #loo.get_n_splits(X_train_std)
----> 5 for train, test in loo.split(X_train_std):
      6     print("%s %s" % (train, test))

AttributeError: 'LeaveOneOut' 对象没有属性'split'

详细代码如下:

from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = 
train_test_split(X, y, test_size=0.3, random_state=0)

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
sc.fit(X_train)
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)

from sklearn.cross_validation import LeaveOneOut
num_of_examples = len(X_train_std)
loo = LeaveOneOut(num_of_examples)
for train, test in loo.split(X_train_std):
print("%s %s" % (train, test))

【问题讨论】:

  • 来自文档 (scikit-learn.org/stable/modules/generated/…) 看来您需要先使用 loo.get_n_splits(X_train) 拆分您的集合
  • 请附上完整的错误信息。
  • 这是无法阅读的。请编辑您的原始问题并在其中包含完整的错误消息。
  • @DYZ 我修改了我的初始帖子。

标签: python scikit-learn cross-validation


【解决方案1】:

我认为您使用的是 0.18 以下的 scikit-learn 版本,可能会参考 0.18 版本的一些教程。

在 0.18 之前的版本中,LeaveOneOut() 构造函数有一个必需参数 n,您发布的上述代码中未提供该参数。因此错误。您可以参考documentation of LeaveOneOut for version 0.17 here,其中提到:

参数:n : int 数据集中元素的总数。

解决方案:

  • 将 scikit-learn 更新到 0.18 版
  • 如下初始化LeaveOneOut

    loo = LeaveOneOut(size of X_train_std)

编辑

如果您使用的是 scikit 版本 >=0.18:

from sklearn.model_selection import LeaveOneOut
for train_index, test_index in loo.split(X):
    print("%s %s" % (train_index, test_index))
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

否则,对于 loo.split(),直接使用loo):

from sklearn.cross_validation import LeaveOneOut
loo = LeaveOneOut(num_of_examples)
for train_index, test_index in loo:
    print("%s %s" % (train_index, test_index))
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

【讨论】:

  • 我已经进行了必要的更改以删除以前的错误,但我确实有另一个错误,我不知道如何解决它。我再次修改了我的初始代码
  • @Shelly 您使用的是什么版本的 scikit?我已经编辑了答案以反映更改。
  • Kumer 如果我使用这个:from sklearn.model_selection import LeaveOneOut 我会收到这个错误:ImportError: No module named 'sklearn.model_selection' 指的是我的 scikit 版本不高于 0.18。我的初始代码中的错误不是因为使用“from sklearn.cross_validation import LeaveOneOut”
  • @Shelly 好的。我已编辑答案以反映更改
  • 即使这样更改也无法使代码正确。我再次收到错误:NameError 11 loo = LeaveOneOut(num_of_examples) 12 for train_index, test_index in loo: ---> 13 print("%s %s" % (train, test)) 14 NameError: name 'train' is未定义
【解决方案2】:

使用

from sklearn.model_selection import train_test_split

而不是cross_validation,因为cross_validation 变成了model_selction

【讨论】:

  • 请详细解释你的答案,并以更易读的格式写出来。
猜你喜欢
  • 2023-03-04
  • 2013-01-24
  • 2021-05-24
  • 2012-05-18
  • 2015-01-13
  • 2013-01-03
  • 2015-09-26
  • 2020-09-16
  • 1970-01-01
相关资源
最近更新 更多