You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Logistic回归模型K折交叉验证Python代码报错求助及修复

Logistic回归StratifiedKFold交叉验证KeyError修复方案

错误原因

你遇到的两个KeyError本质都是数据索引方式错误:

  1. None of [Int64Index(...)] are in the [columns]:直接用X[train_idx]访问DataFrame时,[]默认按列名查找,而train_idx是行索引,导致被误判为列名,找不到对应列。
  2. KeyError:0:通常是后续对一维数组(比如预测结果)使用二维索引,或者数据划分后结构不匹配导致的索引错位。

修复后的完整代码

以下代码实现了正确的K折交叉验证,并输出指定格式的训练/测试精度:

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import accuracy_score

# 替换成你的数据加载逻辑(示例用鸢尾花数据集)
from sklearn.datasets import load_iris
data = load_iris()
X = data.data  # 若为DataFrame,用 df.drop('目标列名', axis=1)
y = data.target  # 若为DataFrame,用 df['目标列名']

# 初始化模型与交叉验证器
log_reg = LogisticRegression(max_iter=1000, random_state=42)
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

train_accuracies = []
test_accuracies = []

# 执行交叉验证
for fold_num, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):
    # 核心修复:正确提取训练/测试集
    # 若X是DataFrame,改用 X.iloc[train_idx]、X.iloc[test_idx]
    X_train, X_test = X[train_idx], X[test_idx]
    y_train, y_test = y[train_idx], y[test_idx]
    
    # 训练与预测
    log_reg.fit(X_train, y_train)
    train_pred = log_reg.predict(X_train)
    test_pred = log_reg.predict(X_test)
    
    # 计算精度
    train_acc = accuracy_score(y_train, train_pred)
    test_acc = accuracy_score(y_test, test_pred)
    
    train_accuracies.append(train_acc)
    test_accuracies.append(test_acc)
    
    # 输出单折结果
    print(f"第 {fold_num} 折")
    print(f"训练精度: {train_acc:.4f}")
    print(f"测试精度: {test_acc:.4f}\n")

# 输出整体结果
print("===== 交叉验证汇总 =====")
print(f"平均训练精度: {np.mean(train_accuracies):.4f} (标准差: {np.std(train_accuracies):.4f})")
print(f"平均测试精度: {np.mean(test_accuracies):.4f} (标准差: {np.std(test_accuracies):.4f})")

关键修复点

  1. 数据提取方式:
    • 若X是numpy.ndarray:直接用X[train_idx]提取行
    • 若X是pandas.DataFrame:必须用X.iloc[train_idx](按位置索引取行),不能用X[train_idx](默认按列名查找)
  2. 索引一致性:确保X的行索引与y的索引完全匹配,避免数据对齐错误
  3. 模型收敛性:设置max_iter=1000避免Logistic回归因迭代次数不足导致的不收敛问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:10:52