You need to enable JavaScript to run this app. K折交叉验证触发KeyError:None of [Int64Index…] are in the [columns]如何解决
优惠活动
大模型
产品
解决方案
定价
更多

K折交叉验证触发KeyError:None of [Int64Index…] are in the [columns]如何解决

报错原因
  • 直接原因:Pandas 索引逻辑错误
    你使用X_train[train_idx]写法时,Pandas会默认将传入的整数列表判定为列名进行匹配,你的数据集不存在对应名称的列,直接触发KeyError。如果要按行位置索引数据,需要使用.iloc属性。
  • 逻辑错误:K折切分对象和实际使用数据集不匹配
    你调用Kfold.split(feat)是基于全量特征数据集生成的行索引,索引范围和长度都和train_test_split拆分得到的X_train完全不一致,就算修复索引写法也会出现切分错误或者索引越界问题。
  • 次要bug:你的打印语句写死了折数为1,运行时所有折都会输出Fold #1。
修复代码

如果你的需求是在训练集上执行K折交叉验证,修改后代码如下:

Kfold = KFold(n_splits=10)
pipeline = make_pipeline(StandardScaler(), DecisionTreeClassifier())
# 直接基于训练集生成K折索引
for fold_num, (train_idx, test_idx) in enumerate(Kfold.split(X_train), start=1):
    # 用iloc按行位置取数
    pipeline.fit(X_train.iloc[train_idx], y_train.iloc[train_idx])
    score = pipeline.score(X_train.iloc[test_idx], y_train.iloc[test_idx])
    print(f'Fold #{fold_num} accuracy: {score}')

如果你需要在全量数据集上做交叉验证,不需要提前执行train_test_split拆分,直接将feat和target传入K折流程即可。

内容的提问来源于stack exchange,提问作者mono

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 21:45:03