【问题标题】:How to calculate the average value of Accuracy, FPR, FNR in a multiclass classification in Python?如何在 Python 中计算多类分类中的 Accuracy、FPR、FNR 的平均值?
【发布时间】:2019-09-29 00:08:52
【问题描述】:

我正在研究 python 中的多类分类(4 类)。 为了分别获取每个类的结果,我使用了以下代码:

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
cnf_matrix = cm
FP = cnf_matrix.sum(axis=0) - np.diag(cnf_matrix)  
FN = cnf_matrix.sum(axis=1) - np.diag(cnf_matrix)
TP = np.diag(cnf_matrix)
TN = cnf_matrix.sum() - (FP + FN + TP)

FP = FP.astype(float)
FN = FN.astype(float)
TP = TP.astype(float)
TN = TN.astype(float)

# Sensitivity, hit rate, recall, or true positive rate
TPR = TP/(TP+FN)
print('TPR : ',TPR)

# Specificity or true negative rate
TNR = TN/(TN+FP)
print('TNR : ',TNR)

# Precision or positive predictive value
PPV = TP/(TP+FP)
print('PPV : ',PPV)

# Fall out or false positive rate
FPR = FP/(FP+TN)
print('FPR : ',FPR)
# False negative rate
FNR = FN/(TP+FN)
print('FNR : ',FNR)
# Overall accuracy
ACC = (TP+TN)/(TP+FP+FN+TN)
print('ACC : ',ACC)

我得到了以下结果:

TPR :  [0.98398792 0.99999366 0.99905393 0.99999548]
TNR :  [0.99999211 0.99997989 1.         0.99773928]
PPV :  [0.99988488 0.99996832 1.         0.99810887]
FPR :  [7.89469529e-06 2.01061605e-05 0.00000000e+00 2.26072224e-03]
FNR :  [1.60120846e-02 6.33705530e-06 9.46073794e-04 4.52196090e-06]
ACC :  [0.99894952 0.99998524 0.99999754 0.99896674]

现在,我想计算每个指标的平均值?!我应该将这四个值相加,然后将结果除以 4 吗?例如,对于准确度 (ACC):(0.99894952 + 0.99998524 + 0.99999754 + 0.99896674)/4 ?!! 或者我应该怎么做? 请帮忙。

【问题讨论】:

  • 是的,平均计算方式就是你说的,这有什么问题?
  • 感谢您的回答,先生,我用这种方法计算了Acc,结果是:0.99947476。之后我使用了:“from sklearn.metrics import accuracy_score”“accuracy_score(y_test,y_pred)”,结果不同了:0.99894952 为什么?第二种方法应该直接给我平均结果,但它与我之前提到的方式不同。
  • 你好,我还没有使用from sklearn.metrics import accuracy_score,我也不知道为什么,但是0.99947476的答案是真的,这样算

标签: python machine-learning multiclass-classification


【解决方案1】:

准确率是正确预测总数除以预测总数。现在假设您有一个包含 45 个条目的数据集,其中包含 4 个类。

class 1: 10 rows
class 2: 10 rows
class 3: 10 rows
class 4: 15 rows

现在每类准确率是

class 1: 1 (10/10)
class 2: 1 (10/10)
class 3: 1 (10/10)
class 4: 0.33 (5/15)

现在,如果您将所有准确率相加并除以 4,即您的方法,答案将是 0.83

如果将正确预测的总数相加,即 45 个中的 35 个,则准确度为 35/45 = 0.77

所以两种方法都不一样。取平均准确率的方法,即你正在做的事情只有在所有类都平衡的情况下才有效,否则它是错误的方法。

您应该计算正确预测的总数并将其除以预测总数,即correct / (correct+wrong)

【讨论】:

    猜你喜欢
    • 2020-05-16
    • 2015-01-05
    • 2013-09-01
    • 2013-12-18
    • 2018-09-15
    • 1970-01-01
    • 2021-08-12
    • 2018-04-21
    • 2011-12-04
    相关资源
    最近更新 更多