收到KeyError:“ [Int64Index([... dtype ='int64',length = 1323)]都不在[列]中”

mar*_*tay 6 python numpy python-3.x pandas scikit-learn

摘要

将测试数据和训练数据输入到ROC曲线图中时,出现以下错误:

KeyError:“ [Int64Index([0,1,2,... dtype ='int64',length = 1323)]都不在[列]中”

该错误似乎是在说它不喜欢我的数据格式,但是在第一次运行时它就起作用了,而且我无法使其再次运行。

我是不正确地分割数据还是将错误格式的数据发送到函数中?

我尝试过的

  • 通读具有相同KeyError的多个StackOverflow帖子
  • 通过我跟随的scikit-learn示例重新学习
  • 查看了我的代码的先前版本以进行故障排除

我正在CoLab文档中运行此文件,可以在此处查看

我正在使用标准数据框提取我的X和Y集:

X = df_full.drop(['Attrition'], axis=1)
y = df_full['Attrition'].as_matrix()
Run Code Online (Sandbox Code Playgroud)

KeyError可追溯到此处的第8行:

def roc_plot(X, Y, Model):
    tprs = []
    aucs = []
    mean_fpr = np.linspace(0, 1, 100)
    plt.figure(figsize=(12,8))
    i = 0
    for train, test in kf.split(X, Y):
        probas_ = model.fit(X[train], Y[train]).predict_proba(X[test])
        # Compute ROC curve and area the curve
        fpr, tpr, thresholds = roc_curve(Y[test], probas_[:, 1])
        tprs.append(np.interp(mean_fpr, fpr, tpr))
        tprs[-1][0] = 0.0
        roc_auc = auc(fpr, tpr)
        aucs.append(roc_auc)
        plt.plot(fpr, tpr, lw=1, alpha=0.3,
                 label='ROC fold %d (AUC = %0.2f)' % (i, roc_auc))

        i += 1
    plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',
             label='Chance', alpha=.8)

    mean_tpr = np.mean(tprs, axis=0)
    mean_tpr[-1] = 1.0
    mean_auc = auc(mean_fpr, mean_tpr)
    std_auc = np.std(aucs)
    plt.plot(mean_fpr, mean_tpr, color='b',
             label=r'Mean ROC (AUC = %0.2f $\pm$ %0.2f)' % (mean_auc, std_auc),
             lw=2, alpha=.8)

    std_tpr = np.std(tprs, axis=0)
    tprs_upper = np.minimum(mean_tpr + std_tpr, 1)
    tprs_lower = np.maximum(mean_tpr - std_tpr, 0)
    plt.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2,
                     label=r'$\pm$ 1 std. dev.')

    plt.xlim([-0.05, 1.05])
    plt.ylim([-0.05, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver operating characteristic example')
    plt.legend(loc="lower right")
    plt.show()
Run Code Online (Sandbox Code Playgroud)

当我使用该函数运行以下命令时,就会发生这种情况:

model = XGBClassifier() # Create the Model
roc_plot(X, Y, Model)
Run Code Online (Sandbox Code Playgroud)

预期结果

我应该能够将X和Y数据输入到函数中。

ale*_*kov 5

这段代码中train, test是索引数组,当从 DataFrame 中选择时将其用作列:

for train, test in kf.split(X, Y):
    probas_ = model.fit(X[train], Y[train]).predict_proba(X[test])
Run Code Online (Sandbox Code Playgroud)

你应该使用iloc

    probas_ = model.fit(X.iloc[train], Y.iloc[train]).predict_proba(X.iloc[test])
Run Code Online (Sandbox Code Playgroud)