首页 > 解决方案 > 尝试在 Python 中获取 False Negative 时获取“索引 1 超出范围”

问题描述

我正在尝试为我的预测获取 TP、TN、FP 和 FN

这是我的代码

xtrain, xval, ytrain, yval = train_test_split(df_features, df_results, test_size=0.2, random_state=9)


clf = RandomForestClassifier(n_estimators=1000, max_depth=10, random_state=0)

clf.fit(xtrain, ytrain)

y_pred = clf.predict(xval)

CM = confusion_matrix(yval, y_pred)

TN = CM[0][0]
FN = CM[1][0]
TP = CM[1][1]
FP = CM[0][1]

我得到了 TN 值,但是当我尝试获取 FN 值时,我得到了这个错误

CM[1][0]
Traceback (most recent call last):

  File "<ipython-input-18-4e0323bdbf74>", line 1, in <module>
    CM[1][0]

IndexError: index 1 is out of bounds for axis 0 with size 1

我该如何解决?

编辑 :

print(CM)
[[19]]

这就是 yval 的样子

yval

6     A72
46    B83
26    B88
76    A94
28    B99
38    A72
61    A72
3     B88
20    A29
45    C52
86    A75

标签: pythonconfusion-matrix

解决方案


将它放在 try-catch 块中以避免错误:

try:
    Precision = cm[0][0]/(cm[0][0] + cm[1][0])
    Recall = cm[0][0]/(cm[0][0] + cm[0][1])
except:
    pass

推荐阅读