使用 KFold 拆分来拟合模型 return "Not in index"

Use KFold split to fit model return "Not in index"

我有一个这样的数据框:

    Col1    Col2    
10   1        6         
11   3        8        
12   9        4        
13   7        2
14   4        3
15   2        9
16   6        7
17   8        1
18   5        5

我想使用 KFold 交叉验证来拟合我的模型并进行预测。

for train_index, test_index in kf.split(X_train, y_train):

    model.fit(X[train_index], y[train_index])
    y_pred = model.predict(X[test_index])

此代码生成以下错误:

'[1 2 4 7] not in index'

我看到在 KFold.split() 之后,train_index 和 test_index 没有使用数据帧的真实索引号。

所以我无法适应我的模型。

有人有想法吗?

据我所知,您的数据帧的索引从 10 而不是 0 开始,正如您所说,sklearn 的拆分使用从 0 开始的索引。一种解决方案是使用 :

df = df.reset_index(drop=True)

另一种解决方案是在数据帧上使用 .iloc,所以它看起来像(假设 y 是一个数组,如果它是数据帧,你也必须在那里使用 .iloc)。

for train_index, test_index in kf.split(X_train, y_train):
   model.fit(X.iloc[train_index], y[train_index])
   y_pred = model.predict(X.iloc[test_index])

第三种解决方案是将数据框转换为数组。

for train_index, test_index in kf.split(X_train, y_train):
   model.fit(X.values[train_index], y[train_index])
   y_pred = model.predict(X.values[test_index])

编辑:我什至可以看到第 4 个解决方案,这可能是您想要的解决方案。您只需执行 df.index.values[train_index] 即可获取训练集中的索引数组。