【问题标题】:To create a custom metrics for regression according to the rule book of Keras' documentation根据 Keras 文档的规则书为回归创建自定义指标
【发布时间】:2020-09-07 15:51:33
【问题描述】:

我找到了两个主要来源。

  1. A tutorial,不按照规则书做(我宁愿避免)
  2. Keras' documentation(我更喜欢避免意外)

我更喜欢遵循 ​​Keras 的文档以避免内存泄漏,因为对于使用 Keras 的 try custom approaches 的一些人来说就是这种情况。
但是 Keras 在文档中显示的是关于分类的。这不是我的情况。
于是我试着看了一下Keras的源码。正是在文件中:/lib/python3.7/site-packages/tensorflow_core/python/keras/metrics.py。它根本没有帮助我,因为大多数指标(一些例外是分类指标)都是使用包装器完成的,如下代码:

@keras_export('keras.metrics.MeanSquaredError')
class MeanSquaredError(MeanMetricWrapper):
    """Computes the mean squared error between `y_true` and `y_pred`.

    For example, if `y_true` is [0., 0., 1., 1.], and `y_pred` is [1., 1., 1., 0.]
    the mean squared error is 3/4 (0.75).

    Usage:

    ```python
    m = tf.keras.metrics.MeanSquaredError()
    m.update_state([0., 0., 1., 1.], [1., 1., 1., 0.])
    print('Final result: ', m.result().numpy())  # Final result: 0.75
    ```

    Usage with tf.keras API:

    ```python
    model = tf.keras.Model(inputs, outputs)
    model.compile('sgd', metrics=[tf.keras.metrics.MeanSquaredError()])
    ```
    """

    def __init__(self, name='mean_squared_error', dtype=None):
        super(MeanSquaredError, self).__init__(
            mean_squared_error, name, dtype=dtype)

正如您所见,只有构造函数方法,我需要的 udpate_state 方法没有很好的灵感。
我在哪里可以找到它?


python 3.7.7
张量流 2.1.0
keras 应用程序 1.0.8
keras 预处理 1.1.0

【问题讨论】:

    标签: tensorflow keras metrics


    【解决方案1】:

    您可以使用损失函数作为指标,因此您可以扩展keras.losses.Loss。您只需要覆盖call,如documentation所示

    import tensorflow as tf
    
    class MeanSquaredError(tf.keras.losses.Loss):
        
        def call(self, y_true, y_pred):
            y_true = tf.cast(y_true, y_pred.dtype)
            return tf.math.reduce_mean(tf.math.square(y_pred - y_true), axis=-1)
    

    【讨论】:

      猜你喜欢
      • 2010-12-21
      • 2019-01-24
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多