Python 交叉验证问题

Python 交叉验证问题,python,scikit-learn,cross-validation,Python,Scikit Learn,Cross Validation,我想使用省略一个交叉验证。但我得到了以下错误: 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

我想使用省略一个交叉验证。但我得到了以下错误:

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))

我认为您使用的是0.18以下的scikit学习版本,可能还参考了0.18版本的一些教程

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

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

解决方案:

  • 将scikit学习更新至0.18版
  • 按如下方式初始化发酵液:

    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))
    
    loo=LeaveOneOut(X\U系列标准尺寸)

编辑

如果您使用的是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]
否则,对于<0.18版本,请使用如下迭代(注意此处未使用
loo.split()
,直接使用
loo
):

使用


与交叉验证不同,因为交叉验证在文档()中已更改为模型选择

,您需要首先使用
loo拆分集合。获取分割(X\u列)
请包含完整的错误消息。这是无法读取的。请编辑您的原始问题,并在其中包含完整的错误消息。@DYZ我修改了我的初始帖子。我已做了必要的更改以删除以前的错误,但我确实有另一个错误,我不知道如何解决它。我已经修改了我的初始代码again@Shelly您使用的是什么版本的scikit?。我已经编辑了答案以反映更改。Kumer如果我使用此选项:从sklearn.model_selection导入LeaveOnOut,我将得到以下错误:ImportError:没有名为“sklearn.model_selection”的模块,它引用的是我的scikit版本不高于0.18。我的初始代码中的错误不是因为使用了“from sklearn.cross_validation import LeaveOneOut”@Shelly Ok。我对答案进行了编辑,以反映更改7。此更改无法使代码正确。我又犯了一个错误:NameError 11 loo=LeaveOneOut(num_of_示例)12用于训练索引,loo中的测试索引:-->13打印(“%s%s”%(训练,测试))14 NameError:名称“train”未定义请详细解释您的答案,并以可读性更好的格式编写。
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]
from sklearn.model_selection import train_test_split