keras中计算precision和recall的一点思考

本文介绍如何在Keras中自定义精度(precision)、召回率(recall)等评估指标,并通过分解tp、tn、fp、fn来更准确地反映模型性能。提供了具体的Python代码示例。
需要对模型的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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值