【问题标题】:Creating custom conditional metric with Keras使用 Keras 创建自定义条件指标
【发布时间】:2019-01-24 21:24:17
【问题描述】:

我正在尝试使用 keras 为我的神经网络创建以下指标:

Custom Keras metric

其中 d=y_{pred}-y_{true}

y_{pred} 和 y_{true} 都是向量

使用以下代码:

将 keras.backend 导入为 K

def score(y_true, y_pred):
        d=(y_pred - y_true)
        if d<0:
            return K.exp(-d/10)-1
        else:
            return K.exp(d/13)-1

用于编译我的模型:

model.compile(loss='mse', optimizer='adam', metrics=[score])

我收到以下错误代码,但我无法更正该问题。任何帮助将不胜感激。

raise TypeError("Using a tf.Tensor as a Python bool is not 允许。 " "使用if t is not None: 代替if t: 来测试一个" "定义了张量,使用TensorFlow ops如"

TypeError: 不允许将 tf.Tensor 用作 Python bool。采用 if t is not None: 而不是 if t: 来测试是否定义了张量, 并使用 tf.cond 等 TensorFlow 操作来执行子图 以张量的值为条件。

【问题讨论】:

    标签: python tensorflow neural-network keras


    【解决方案1】:

    您提供的指标不是每次都会执行的函数,而是需要评估的函数(计算图)的构造。所以它需要是确定性的。

    试试:

    def score(y_true, y_pred):
        d = y_pred - y_true
        mask = K.less(y_pred, y_true)  # element-wise True where y_pred < y_pred
        mask = K.cast(mask, K.floatx())  # cast to 0.0 / 1.0
        s = mask * (K.exp(-d / 10) - 1) + (1 - mask) * (K.exp(d / 13) - 1)  
        # every i where mask[i] is 1, s[i] == (K.exp(-d / 10) - 1)
        # every i where mask[i] is 0, s[i] == (K.exp(d / 13) - 1)
        return s
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      • 2020-03-04
      • 2017-09-20
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      相关资源
      最近更新 更多