当输出是单热编码时如何计算 CNN 的准确性

数据挖掘 神经网络
2022-02-27 13:31:50

我想计算我的模型在测试数据上的准确性。我有三个类,所以实际输出可能如下所示:

[0 1 0]

并且预测的输出可能如下所示:

[0.1 0.8 0.1]

我如何用这个计算准确性?我应该计算交叉熵并从中减去 1 吗?

2个回答

预测类别是输出向量中概率最高的类别(在您的情况下为 B 类),并且准确性是正确的预测百分比,除非我错过了您的观点。

您提到的问题是多类分类的代表,它是使用中性网络中的 Softmax 输出层解决的。请注意,Softmax 使用交叉熵作为损失函数。

我觉得计算输出的交叉熵可能没有意义。

如果我理解您的问题,在上面的示例中,您有三个类,它们是单热编码的。例如,

actual = [0 1 0]
pred = [0.1 0.8 0.1]

要在这种情况下找到准确性,您要做的是获取 actual_labels 和 pred_labels 中具有最大值的元素的索引:

act_label = numpy.argmax(actual) # act_label = 1 (index)
pred_label = numpy.argmax(pred) # pred_label = 1 (index)

对数据中的每个实例执行此操作,并在这些索引匹配时增加 number_of_correct_predictions

correct = 0
total = 0
for i in range(len(data)):
    act_label = numpy.argmax(actual[i]) # act_label = 1 (index)
    pred_label = numpy.argmax(pred[i]) # pred_label = 1 (index)
    if(act_label == pred_label):
        correct += 1
    total += 1
accuracy = (correct/total)

尽管这是完成工作的一种非常基本的方法,但确实存在这种方法的更简化版本,只需几行代码。

如果您不介意为此使用库,可以在 sklearn 中使用:

from sklearn.metrics import accuracy_score

accuracy = accuracy_score(y_true=actual, y_pred=pred) # Also gives the accuracy for the two lists actual and pred