怎样才能从张量流或Keras中的混淆矩阵中得到准确度呢?

2024-06-09 20:24:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从混淆矩阵中得到UAR(未加权精度)来监控验证数据的UAR。然而,张量的处理是困难的。在

https://www.davidtvs.com/keras-custom-metrics/

我确实参考了这个站点,并尝试在Keras中创建自己的度量标准。 我通过使用第一个方法同时使用Keras支持的ModelCheckpoint和{}来生成度量。在

model.compile(loss='categorical_crossentropy',optimizer=adam, metrics=['accuracy', uar_accuracy])

但是,我不知道如何定义uar_accuracy函数。在

^{pr2}$

此结果返回每个类的右侧数据数的平均值。 但我不需要正确数据数量的平均值,而是每个类的正确概率的平均值。

我如何实施?在

我已经为numpy类型实现了以下内容,而不是使用sklearn.metricscollections库的张量类型

            def get_accuracy_and_cnf_matrix(label, predict):
            uar = 0
            accuracy = []
            cnf_matrix = confusion_matrix(label, predict)
            diag=np.diagonal(cnf_matrix)
            for index,i in enumerate(diag):
                uar+=i/collections.Counter(label)[index]

            # cnf_marix (Number of corrects -> Accuracy)    
            cnf_matrix = np.transpose(cnf_matrix)
            cnf_matrix = cnf_matrix*100 / cnf_matrix.astype(np.int).sum(axis=0)
            cnf_matrix = np.transpose(cnf_matrix).astype(float)
            cnf_matrix = np.around(cnf_matrix, decimals=2)   

            # WAR, UAR
            test_weighted_accuracy = np.sum(label==predict)/len(label)*100
            test_unweighted_accuracy = uar/len(cnf_matrix)*100    
            accuracy.append(test_weighted_accuracy)
            accuracy.append(test_unweighted_accuracy)

            return np.around(np.array(accuracy),decimals=2), cnf_matrix  

Tags: 数据test类型度量nppredictmatrixlabel
1条回答
网友
1楼 · 发布于 2024-06-09 20:24:23

您可以使用tf.reduce_sum来计算混淆矩阵中每一行的总和。这对应于每个类的数据点总数。然后用行和除以对角线元素,以计算每个类正确预测的示例的比率。在

def non_nan_average(x):
    # Computes the average of all elements that are not NaN in a rank 1 tensor
    nan_mask = tf.debugging.is_nan(x)
    x = tf.boolean_mask(x, tf.logical_not(nan_mask))
    return K.mean(x)


def uar_accuracy(y_true, y_pred):
    # Calculate the label from one-hot encoding
    pred_class_label = K.argmax(y_pred, axis=-1)
    true_class_label = K.argmax(y_true, axis=-1)

    cf_mat = tf.confusion_matrix(true_class_label, pred_class_label )

    diag = tf.linalg.tensor_diag_part(cf_mat)    

    # Calculate the total number of data examples for each class
    total_per_class = tf.reduce_sum(cf_mat, axis=1)

    acc_per_class = diag / tf.maximum(1, total_per_class)  
    uar = non_nan_average(acc_per_class)

    return uar

相关问题 更多 >