【问题标题】:AxisError: axis 1 is out of bounds for array of dimension 1 when calculating AUCAxisError:计算 AUC 时,轴 1 超出维度 1 数组的范围
【发布时间】:2020-07-31 23:29:25
【问题描述】:

我有一个分类问题,我有一个 8x8 图像的像素值和图像表示的数字,我的任务是使用 RandomForestClassifier 根据像素值预测数字(“数字”属性)。数值的值可以是0-9。

from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score

forest_model = RandomForestClassifier(n_estimators=100, random_state=42)
forest_model.fit(train_df[input_var], train_df[target])
test_df['forest_pred'] = forest_model.predict_proba(test_df[input_var])[:,1]
roc_auc_score(test_df['Number'], test_df['forest_pred'], average = 'macro', multi_class="ovr")

这里会抛出一个 AxisError。

回溯(最近一次通话最后): 文件“dap_hazi_4.py”,第 44 行,在 roc_auc_score(test_df['Number'], test_df['forest_pred'], average = 'macro', multi_class="ovo") 文件“/home/balint/.local/lib/python3.6/site-packages/sklearn/metrics/_ranking.py”,第 383 行,在 roc_auc_score 多类,平均,样本权重) _multiclass_roc_auc_score 中的文件“/home/balint/.local/lib/python3.6/site-packages/sklearn/metrics/_ranking.py”,第 440 行 如果不是 np.allclose(1, y_score.sum(axis=1)): 文件“/home/balint/.local/lib/python3.6/site-packages/numpy/core/_methods.py”,第 38 行,在 _sum return umr_sum(a, axis, dtype, out, keepdims, initial, where) AxisError:轴 1 超出维度 1 数组的范围

【问题讨论】:

  • 我设法解决了我的问题。就是这样,因为我的分类问题是多类的,所以在拟合和计算 auc 分数之前需要对目标列进行二值化。
  • @Bálint Béres 你到底做了什么?
  • 当使用sklearn.model_selection.cross_validate 和类似的并出现此错误时,您只需在make_scorer(roc_auc_score, multi_class='ovo', needs_proba=True) 中设置needs_proba=True

标签: python-3.x scikit-learn multiclass-classification


【解决方案1】:

你确定这个[:,1]test_df['forest_pred'] = forest_model.predict_proba(test_df[input_var])[:,1] 是对的?应该是一维数组

【讨论】:

    【解决方案2】:

    实际上,由于您的问题是多类的,因此标签必须是一次性编码的。 当标签是 one-hot 编码时,'multi_class' 参数起作用。 通过提供 one-hot 编码标签,您可以解决错误。

    假设您有 100 个测试标签,其中包含 5 个唯一类,那么您的矩阵大小(测试标签)必须是 (100,5) NOT (100,1)

    【讨论】:

    • 我在这里遇到了同样的问题。如何将我的 pred(45520,) 转换为 (45520,5)
    • 如果您使用的是 tensorflow 或 keras,您可以使用函数 tf.keras.utils.to_categorical(.) 或仅使用 keras.utils.to_categorical(.)
    【解决方案3】:

    该错误是由于您按照其他人的建议解决的多类问题。您需要做的不是预测类别,而是需要预测概率。我之前也遇到过同样的问题,这样做解决了。

    这是怎么做的-

    # you might be predicting the class this way
    pred = clf.predict(X_valid)
    
    # change it to predict the probabilities which solves the AxisError problem.
    pred_prob = clf.predict_proba(X_valid)
    roc_auc_score(y_valid, pred_prob, multi_class='ovr')
    0.8164900342274142
    
    # shape before
    pred.shape
    (256,)
    pred[:5]
    array([1, 2, 1, 1, 2])
    
    # shape after
    pred_prob.shape
    (256, 3)
    pred_prob[:5]
    array([[0.  , 1.  , 0.  ],
           [0.02, 0.12, 0.86],
           [0.  , 0.97, 0.03],
           [0.  , 0.8 , 0.2 ],
           [0.  , 0.42, 0.58]])
    
    

    【讨论】:

      猜你喜欢
      • 2022-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-30
      • 2018-07-07
      • 1970-01-01
      • 2018-05-22
      相关资源
      最近更新 更多