• keras.metrics解析


    前言

    metrics用于判断模型性能。度量函数类似于损失函数,只是度量的结果不用于训练模型。可以使用任何损失函数作为度量(如logloss等)。在训练期间监控metrics的最佳方式是通过Tensorboard

    官方提供的metrics最重要的概念就是有状态(stateful)变量,通过更新状态变量,可以不断累积统计数据,并可以随时输出状态变量的计算结果。这是区别于losses的重要特性,losses是无状态的(stateless)。

    本文部分内容参考了:

    代码运行环境为:tf.__version__==2.6.2 。

    metrics原理解析(以metrics.Mean为例)

    metrics是有状态的(stateful),即Metric 实例会存储、记录和返回已经累积的结果,有助于未来事务的信息。下面以tf.keras.metrics.Mean()为例进行解释:

    创建tf.keras.metrics.Mean的实例:

    m = tf.keras.metrics.Mean()
    
    • 1

    通过help(m) 可以看到MRO为:

    Mean
    Reduce
    Metric
    keras.engine.base_layer.Layer
    ...
    
    • 1
    • 2
    • 3
    • 4
    • 5

    可见Metric和Mean是 keras.layers.Layer 的子类。相比于类Layer,其子类Mean多出了几个方法:

    • r e s u l t \mathsf{result} result: 计算并返回标量度量值(tensor形式)或标量字典,即状态变量简单地计算度量值。例如,m.result(),就是计算均值并返回
    • t o t a l \mathsf{total} total: 状态变量m目前累积的数字总和
    • c o u n t \mathsf{count} count: 状态变量m目前累积的数字个数(m.total/m.count就是m.result()的返回值)
    • u p d a t e _ s t a t e \mathsf{update\_state} update_state: 累积统计数字用于计算指标。每次调用m.update_state都会更新m.totalm.count
    • r e s e t _ s t a t e \mathsf{reset\_state} reset_state: 将状态变量重置到初始化状态;
    • r e s e t _ s t a t e s \mathsf{reset\_states} reset_states: 等价于reset_state,参见keras源代码metrics.py L355
    • r e d u c t i o n \mathsf{reduction} reduction: 目前来看,没什么用。

    这也决定了Mean的特殊性质。其使用参见如下代码:

    # 创建状态变量m,由于m未刚初始化,
    # 所以total,count和result()均为0
    m = tf.keras.metrics.Mean()
    print("m.total:",m.total)
    print("m.count:",m.count)
    print("m.result():",m.result())
    
    """
    # 输出:
    m.total: 
    m.count: 
    m.result(): tf.Tensor(0.0, shape=(), dtype=float32)
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    # 更新状态变量,可以看到total累加了总和,
    # count累积了个数,result()返回total/count
    m.update_state([1,2,3])
    print("m.total:",m.total)
    print("m.count:",m.count)
    print("m.result():",m.result())
    
    """
    # 输出:
    m.total: 
    m.count: 
    m.result(): tf.Tensor(2.0, shape=(), dtype=float32)
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    # 重置状态变量, 重置到初始化状态
    m.reset_state()
    print("m.total:",m.total)
    print("m.count:",m.count)
    print("m.result():",m.result())
    
    
    """
    # 输出:
    m.total: 
    m.count: 
    m.result(): tf.Tensor(0.0, shape=(), dtype=float32)
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    创建自定义metrics

    创建无状态 metrics

    与损失函数类似,任何带有类似于metric_fn(y_true, y_pred)、返回损失数组(如输入一个batch的数据,会返回一个batch的损失标量)的函数,都可以作为metric传递给compile()

    import tensorflow as tf
    import numpy as np
    
    inputs = tf.keras.Input(shape=(3,))
    x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
    outputs = tf.keras.layers.Dense(1, activation=tf.nn.softmax)(x)
    model1 = tf.keras.Model(inputs=inputs, outputs=outputs)
    
    def my_metric_fn(y_true, y_pred):
        squared_difference = tf.square(y_true - y_pred)
        return tf.reduce_mean(squared_difference, axis=-1) # shape=(None,)
    
    model1.compile(optimizer='adam', loss='mse', metrics=[my_metric_fn])
    
    x = np.random.random((100, 3))
    y = np.random.random((100, 1))
    model1.fit(x, y, epochs=3)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    输出:

    Epoch 1/3
    4/4 [==============================] - 0s 667us/step - loss: 0.0971 - my_metric_fn: 0.0971
    Epoch 2/3
    4/4 [==============================] - 0s 667us/step - loss: 0.0958 - my_metric_fn: 0.0958
    Epoch 3/3
    4/4 [==============================] - 0s 1ms/step - loss: 0.0946 - my_metric_fn: 0.0946
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    注意,因为本例创建的是无状态的度量,所以上面跟踪的度量值(my_metric_fn后面的值)是每个batch的平均度量值,并不是一个epoch(完整数据集)的累积值。(这一点需要理解,这也是为什么要使用有状态度量的原因!)

    值得一提的是,如果上述代码使用

    model1.compile(optimizer='adam', loss='mse', metrics=["mse"])
    
    • 1

    进行compile,则输出的结果是累积的,在每个epoch结束时的结果就是整个数据集的结果,因为metrics=["mse"]是直接调用了标准库的有状态度量。


    通过继承Metric创建有状态 metrics

    如果想查看整个数据集的指标,就需要传入有状态的metrics,这样就会在一个epoch内累加,并在epoch结束时输出整个数据集的度量值。

    创建有状态度量指标,需要创建Metric的子类,它可以跨batch维护状态,步骤如下:

    • __init__中创建状态变量(state variables)
    • 更新update_state()y_truey_pred的变量
    • result()中返回标量度量结果
    • reset_states()中清除状态
    class BinaryTruePositives(tf.keras.metrics.Metric):
    
        def __init__(self, name='binary_true_positives', **kwargs):
            super(BinaryTruePositives, 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_true = tf.cast(y_true, tf.bool)
            y_pred = tf.cast(y_pred, tf.bool)
    
            values = tf.logical_and(tf.equal(y_true, True), tf.equal(y_pred, True))
            values = tf.cast(values, self.dtype)
            if sample_weight is not None:
                sample_weight = tf.cast(sample_weight, self.dtype)
                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):
            self.true_positives.assign(0)
    
    m = BinaryTruePositives()
    m.update_state([0, 1, 1, 1], [0, 1, 0, 0])
    print('Intermediate result:', float(m.result()))
    
    m.update_state([1, 1, 1, 1], [0, 1, 1, 0])
    print('Final result:', float(m.result()))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    add_metric() 方法

    add_metric 方法是 tf.keras.layers.Layer类添加的方法,Layer的父类tf.Module并没有这个方法,因此在编写Layer子类如包括自定义层、官方提供的层(Dense)或模型(tf.keras.Model也是Layer的子类)时,可以使用add_metric()来与层相关的统计量。比如,将类似Dense的自定义层的激活平均值记录为metric。可以执行以下操作:

    class DenseLike(Layer):
        """y = w.x + b"""
        ...
        def call(self, inputs):
            output = tf.matmul(inputs, self.w) + self.b
            self.add_metric(tf.reduce_mean(output), aggregation='mean', name='activation_mean')
            return output
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    将在名称为activation_mean的度量下跟踪output,跟踪的值为每个批次度量值的平均值。

    更详细的信息,参阅官方文档The base Layer class - add_metric method

    参考

    Keras-Metrics官方文档

  • 相关阅读:
    图书管理系统C语言课程设计
    安全协议缺陷
    java计算机毕业设计中医保健网站源码+系统+lw+数据库+调试运行
    SSTV慢速扫描的几种模式优劣对比
    技术策划学习 —— 引擎工具链高级概念与应用
    WebGL(ThreeJS)加载乐高Ldraw模型案例
    邮件钓鱼的防守策略
    C#开源实用的工具类库,集成超过1000多种扩展方法
    本地化小程序运营 同城小程序开发
    软考-软件开发模型
  • 原文地址:https://blog.csdn.net/u012762410/article/details/127609836