AxisError:在计算AUC时,轴1超出了维度为1的数组的界限



我有一个分类问题,我有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。

Traceback(最近一次通话最后一次(:文件"dap_hazi_4.py",第44行,位于roc_auc_score(test_df['Number'],test_df='rest_pred'],average='macro',multi_class="ovo"(文件"/home/balint/.local/lib/python3.6/site packages/sklearn/metrics/ranking.py",第383行,在roc_auc_score中multi_class,average,sample_weight(文件"/home/balint/.local/lib/python3.6/site packages/sklearn/metrics/ranking.py",第440行,在_multiclass_roc_auc_score中如果不是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的数组的界限

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

以下是如何做到这一点-

# 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]])

实际上,由于问题是多类,标签必须是一个热编码的。当标签是一个热编码时,"multi_class"参数就起作用了。通过提供一个热编码标签,您可以解决错误。

假设你有100个测试标签和5个唯一的类,那么你的矩阵大小(测试标签的(必须是(100,5(NOT(100,1(

您确定test_df['forest_pred'] = forest_model.predict_proba(test_df[input_var])[:,1]中的此[:,1]是吗?可能是1D阵列

最新更新