【问题标题】:How can I do K fold cross-validation for splitting the train and test set?如何进行 K 折交叉验证以拆分训练集和测试集?
【发布时间】:2016-05-12 12:36:11
【问题描述】:

我有一组文档和一组标签。 现在,我正在使用 train_test_split 以 90:10 的比例拆分我的数据集。但是,我希望使用 Kfold 交叉验证。

train=[]

with open("/Users/rte/Documents/Documents.txt") as f:
    for line in f:
        train.append(line.strip().split())

labels=[]
with open("/Users/rte/Documents/Labels.txt") as t:
    for line in t:
        labels.append(line.strip().split())

X_train, X_test, Y_train, Y_test= train_test_split(train, labels, test_size=0.1, random_state=42)

当我尝试 scikit learn 文档中提供的方法时:我收到一条错误消息:

kf=KFold(len(train), n_folds=3)

for train_index, test_index in kf:
     X_train, X_test = train[train_index],train[test_index]
     y_train, y_test = labels[train_index],labels[test_index]

错误

   X_train, X_test = train[train_index],train[test_index]
TypeError: only integer arrays with one element can be converted to an index

如何对我的文档和标签执行 10 折交叉验证?

【问题讨论】:

  • 到目前为止,为了让 Kfold 交叉验证发挥作用,您做了哪些尝试?你看过documentation page上的例子吗?
  • 是的,我已经在我的文档和标签集上尝试了那里给出的示例,但我收到一个错误:X_train, X_test = train[train_index],train[test_index] TypeError: only integer arrays一个元素可以转换为索引

标签: python scikit-learn


【解决方案1】:

有两种方法可以解决这个错误:

第一种方式:

将数据转换为 numpy 数组:

import numpy as np
[...]
train = np.array(train)
labels = np.array(labels)

那么它应该适用于您当前的代码。

第二种方式:

使用列表推导通过 train_index 和 test_index 列表索引训练和标签列表

for train_index, test_index in kf:
    X_train, X_test = [train[i] for i in train_index],[train[j] for j in test_index]
    y_train, y_test = [labels[i] for i in train_index],[labels[j] for j in test_index]

(有关此解决方案,另请参阅相关问题index list with another list

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-17
    • 2018-12-07
    • 2018-05-03
    • 2011-12-16
    • 2021-03-04
    • 2016-01-29
    • 1970-01-01
    • 2018-04-03
    相关资源
    最近更新 更多