需要对模型的precision和recall进行衡量,希望使用metrics在训练的时候将这两个指标体现出来。
keras2.0中已经删除了F1score、precision和recall的计算。按照
https://github.com/keras-team/keras/issues/5400) 的说法,可以自己编写batch_wise的precision和recall。自定义了如下的代码。
def precision(y_true,y_pred,n=0):#精准率
threshold = K.constant(n)
true_positives = K.sum(K.cast(K.greater(y_true,threshold)&K.greater(y_pred,threshold),tf.float32))
possible_positives = K.sum(K.cast(K.greater(y_pred,threshold),tf.float32))
precision = true_positives / (possible_positives + K.epsilon())
return precision
def recall(y_true,y_pred,n=0):#召回率
threshold = K.constant(n)
true_positives = K.sum(K.cast(K.greater(y_true,threshold)&K.greater(y_pred,threshold),tf.float32))
possible_positives = K.sum(K.cast(K.greater(y_true,threshold),tf.float32))
recall = true_positives / (possible_positives + K.epsilon())
return recall
代码设置了个阈值n,精准率是预测值中大于n的数量中,真实值也大于n的比例。召回率是真实值大于n的数量中,预测值也大于n的比例。
然而,越测试越感觉不对,batch_wise的结果是我们想要的吗?问题出在一个batch中TP都为0的情况下,此时precision的计算结果为0;而分母并非全都非0的,为0的数字不该记到分母的总和里面去。当batch很小,或者准确率很低的情况下问题就会很突出。显示的结果不能反映真实的情况。
所以直接使用Batch_wise的指标是不行的,原因是里面的触发。但是如果换个思路呢?不直接使用precision、recall这类指标,而是取分解的tp、tn、fp、fn,这几个指标可以在batch里求平均,再在整个epoch上平均就是它本身的平均值,因为里面的除法的分母都是batchsize。而precision=tp/(tp+fp),recall =tp/(tp+tn),total_accuracy =(tp+fn)/(tp+fn+tn+fp)
重新定义了四个函数:
def tp(y_true,y_pred,n=0):#提供真实值大于n且预测值大于n的数量的平均值
threshold = K.constant(n)
true_positives = K.mean(K.cast(K.greater(y_true,threshold)&K.greater(y_pred,threshold),tf.float32))
return true_positives
def tn

本文介绍如何在Keras中自定义精度(precision)、召回率(recall)等评估指标,并通过分解tp、tn、fp、fn来更准确地反映模型性能。提供了具体的Python代码示例。
最低0.47元/天 解锁文章
2073

被折叠的 条评论
为什么被折叠?



