【问题标题】:Use KFold split to fit model return "Not in index"使用 KFold 拆分拟合模型返回“不在索引中”
【发布时间】:2019-05-12 05:44:56
【问题描述】:

我有一个这样的数据框:

    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] 不在索引中'

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

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

有人有想法吗?

【问题讨论】:

  • 我已经对此进行了测试,但这并没有解决我的错误。正如我所说,我的错误在于合适的部分。当我尝试使用.loc 时,使用的索引不是我数据框的真正索引。由于我的数据框中不存在索引,它用NaN 填充值
  • 好的,重新打开。不知道。

标签: python pandas cross-validation


【解决方案1】:

据我所知,您的数据帧的索引从 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] 即可获取训练集中的索引数组。

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    相关资源
    最近更新 更多