【问题标题】:KeyError(f"None of [{key}] are in the [{axis_name}]") when calculating average metrics after Cross ValidationKeyError(f"None of [{key}] are in the [{axis_name}]") 在交叉验证后计算平均指标时
【发布时间】:2022-01-04 22:25:11
【问题描述】:

我正在尝试在执行交叉验证后计算一些平均指标。 执行此操作的函数如下:

from sklearn.model_selection import KFold
from numpy import mean
from numpy import std
from sklearn.metrics import confusion_matrix
from sklearn.linear_model import LogisticRegression

    # Returns average confusion matrix, average accuracy 
    # and average standard deviation after all the cross-validation runs
    def get_average_metrics(model,cv,X_fss,y):
        conf_matrix_list_of_arrays = []
        scores = []
        for train_index, test_index in cv.split(X_fss):
           X_train, X_test = X_fss[train_index], X_fss[test_index]
           y_train, y_test = y[train_index], y[test_index]
           score = model.fit(X_train, y_train).score(X_test, y_test)
           conf_matrix = confusion_matrix(y_test, model.predict(X_test))
           scores.append(score)
           conf_matrix_list_of_arrays.append(conf_matrix)
        # Average confusion matrix
        mean_of_conf_matrix_arrays = mean(conf_matrix_list_of_arrays, axis=0)
        # Average accuracy
        avg_score = mean(scores)
        # Average standard deviation
        std_score = std(scores)
        return avg_score,std_score,mean_of_conf_matrix_arrays

但是,我在X_train, X_test = X_fss[train_index], X_fss[test_index] 行中收到此错误:

KeyError: "没有 [Int64Index([ 1, 2, 4, 5, 6, 7,
9, 10, 11, 12,\n ...\n 1620, 1621, 1622, 1623, 1624, 1625, 1626, 1627, 1629, 1630],\n dtype='int64', 长度=1467)]在[列]"

接收到的函数参数

  • 型号->logistic = LogisticRegression()
  • 简历->cv = KFold(n_splits=10,shuffle=True, random_state=1)
  • X_fss -> 一个 Dataframe 大小 (1631, 4)
  • y -> 系列,大​​小为 (1631,)

X_fss 示例:

y 样本:

【问题讨论】:

    标签: python pandas scikit-learn sklearn-pandas


    【解决方案1】:

    我已经解决了将 X_fss Dataframe 转换为 numpy 数组 的问题:

    X_fss = X_fss.to_numpy()
    

    【讨论】:

      猜你喜欢
      • 2022-12-12
      • 2021-04-01
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      • 2021-01-11
      • 2018-06-01
      • 1970-01-01
      相关资源
      最近更新 更多