【问题标题】:How to write a Keras custom metric that filters or masks some values?如何编写过滤或屏蔽某些值的 Keras 自定义指标?
【发布时间】:2017-10-19 17:12:25
【问题描述】:

在 Keras 中,我试图弄清楚如何计算过滤掉或掩盖某些值的自定义指标或损失,以便它们不会对返回值做出贡献。我被困在如何获取张量切片或如何使用 if: 迭代张量中的值以选择感兴趣的值。

我碰巧在使用 Tensorflow 后端,但想做一些可移植的事情。

附件是我正在尝试做的粗略概述,但它会引发错误:TypeError: 'Tensor' object does not support item assignment

    def my_filtered_mse(y_true, y_pred):
        #Return Mean Squared Error for a subset of values
        error = y_pred - y_true
        error[y_true == 0.0]  =  0 #Don't include errors when y_true is zero
        # The previous like throws the error : TypeError: 'Tensor' object does not support item assignment
        return K.mean(K.square(error))

#...other stuff ...

    model.compile(optimizer=optimizers.adam(), 
        loss='mean_squared_error',
        metrics=[my_filtered_mse]) 

【问题讨论】:

    标签: python tensorflow keras keras-2


    【解决方案1】:

    失败发生在这一行:

    error[y_true == 0.0]  =  0 #Don't include errors when y_true is zero
    

    因为error 是张量,不支持项目分配。您可以将其更改为:

    error = tf.gather(error, tf.where(tf.not_equal(y_true, 0.0)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      • 2020-03-04
      相关资源
      最近更新 更多