【tensorflow2.0】13.常用评估函数及自定义评估函数

    今天是自定义的最后一部分内容:自定义评估函数。

#先介绍一下常用的评估函数
tf.keras.metrics.MeanSquaredError (平方差误差,用于回归,可以简写为MSE,
函数形式为mse)
• tf.keras.metrics.MeanAbsoluteError (绝对值误差,用于回归,可以简写为MAE,
函数形式为mae)
• tf.keras.metrics.MeanAbsolutePercentageError (平均百分比误差,用于回归,
可以简写为MAPE,函数形式为mape)
• tf.keras.metrics.RootMeanSquaredError (均方根误差,用于回归)

tf.keras.metrics.Accuracy (准确率,用于分类,可以用字符串"Accuracy"表示,
Accuracy=(TP+TN)/(TP+TN+FP+FN),要求y_true和y_pred都为类别序号编码)
• tf.keras.metrics.AUC (ROC曲线(TPR vs FPR)下的面积,用于二分类,直观解释为
随机抽取一个正样本和一个负样本,正样本的预测值大于负样本的概率)
• tf.keras.metrics.Precision (精确率,用于二分类,Precision = TP/(TP+FP))
• tf.keras.metrics.Recall (召回率,用于二分类,Recall = TP/(TP+FN))
• tf.keras.metrics.TopKCategoricalAccuracy(多分类TopK准确率,要求
y_true(label)为onehot编码形式)

tf.keras.metrics.CategoricalAccuracy(分类准确率,与Accuracy含义相同,要
求y_true(label)为onehot编码形式)
• tf.keras.metrics. SparseCategoricalAccuracy (稀疏分类准确率,与Accuracy含
义相同,要求y_true(label)为序号编码形式)

    下边是自定义评估函数,和自定义损失函数一样,自定义评估函数也有两种实现形式:基于类(常用)和基于函数的实现
自定义损失函数:
    自定义评估指标需要继承 tf.keras.metrics.Metric 类,并重写 init 、update_state 和 result 三个方法。
init():所有状态变量都应通过以下方法在此方法中创建self.add_weight();
• update_state(): 对状态变量进行所有更新;
• result(): 根据状态变量计算并返回指标值;
• reset_states():这个是对状态变量进行置零,以便于下一轮评估。

'''
下边这段代码就是对于上述三个方法的示例,如果我们中间加入reset_states()方法,那么结果就是0.75,0.5,否则就是0.75,0.625
'''
m=tf.keras.metrics.Accuracy()
m.update_state([1,2,3,4],[0,2,3,4])

print('Final result: ',m.result().numpy())
# Final result: 0.75
#m.reset_states()
m.update_state([1,2,3,4],[0,2,3,1])
print('Final result: ',m.result().numpy())
# Final result: 0.625
#下边是通过类方法实现SparseCategoricalAccuracy,注意,这里是accuracy的评估方法,所以结果是一个百分比
class SparseCategoricalAccuracy_(tf.keras.metrics.Metric):
    def __init__(self, name='SparseCategoricalAccuracy', **kwargs):
        super(SparseCategoricalAccuracy_, self).__init__(name=name, **kwargs)
        #对正确个数和总个数进行置零初始化
        self.total = self.add_weight(name='total', dtype=tf.int32, initializer=tf.zeros_initializer())
        self.count = self.add_weight(name='count', dtype=tf.int32, initializer=tf.zeros_initializer())

	#对状态变量进行更新
    def update_state(self, y_true, y_pred,sample_weight=None):
    	#下边这行代码有点长,初学可以这样写:
    	#values = tf.equal(y_true, tf.argmax(y_pred, axis=-1, output_type=tf.int32))
    	#values = tf.cast(values,tf.int32)
        values = tf.cast(tf.equal(y_true, tf.argmax(y_pred, axis=-1, output_type=tf.int32)), tf.int32)
        self.total.assign_add(tf.shape(y_true)[0])
        self.count.assign_add(tf.reduce_sum(values))
	#这里计算出accuracy
    def result(self):
        return self.count / self.total

    def reset_states(self):
        # The state of the metric will be reset at the start of each epoch.
        self.total.assign(0)
        self.count.assign(0)

s = SparseCategoricalAccuracy_()
# s.reset_states()
s.update_state(tf.constant([2, 1]), tf.constant([[0.1, 0.9, 0.8], [0.05, 0.95, 0]]))
print('Final result: ', s.result().numpy()) 
# Final result: 0.5
#这个是CatgoricalTruePositives,注意这里的TruePositives,指的是正确预测的个数,所以不需要做比,直接输出
class CatgoricalTruePositives(tf.keras.metrics.Metric):
    def __init__(self, name='categorical_true_positives', **kwargs):
        super(CatgoricalTruePositives, self).__init__(name=name, **kwargs)
        self.true_positives = self.add_weight(name='tp', initializer='zeros')

    def update_state(self, y_true, y_pred, sample_weight=None):
        y_pred = tf.argmax(y_pred,axis=-1)
        values = tf.equal(tf.cast(y_true, 'int32'), tf.cast(y_pred, 'int32'))
        values = tf.cast(values, 'float32')
        if sample_weight is not None:
            sample_weight = tf.cast(sample_weight, 'float32')
            values = tf.multiply(values, sample_weight)
        self.true_positives.assign_add(tf.reduce_sum(values))

    def result(self):
        return self.true_positives

    def reset_states(self):
        # The state of the metric will be reset at the start of each epoch.
        self.true_positives.assign(0.)
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值