【发布时间】:2019-01-21 07:14:25
【问题描述】:
我想从混淆矩阵中获取 UAR(未加权准确度)来监控验证数据的 UAR。但是,很难处理张量。
https://www.davidtvs.com/keras-custom-metrics/
我确实参考了这个网站并尝试在 Keras 中创建自己的指标。
我通过使用 Keras 支持的ModelCheckpoint 和EarlyStopping 的第一种方法来制定指标。
model.compile(loss='categorical_crossentropy',optimizer=adam, metrics=['accuracy', uar_accuracy])
但是,我不知道如何定义uar_accuracy 函数。
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)
uar = K.mean(diag)
return uar
此结果返回每个类的数据权数的平均值。 但我不想要正确数据数量的平均值,但我想要每个类别的正确概率的平均值。
我该如何实现它?
我使用sklearn.metrics 和collections 库为numpy 类型而不是Tensor 类型实现了以下内容
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
【问题讨论】:
标签: python tensorflow keras confusion-matrix