【问题标题】:Errors when Building up a Custom Loss Function建立自定义损失函数时的错误
【发布时间】:2019-11-15 20:13:32
【问题描述】:

我尝试建立自己的损失函数如下

    import numpy as np
    from keras import backend as K

    def MyLoss(self, x_input, x_reconstruct):

        a = np.copy(x_reconstruct)
        a = np.asarray(a, dtype='float16')       
        a = np.floor(4*a)/4
        return K.mean(K.square(a - x_input), axis=-1)`

在编译中,它说 ValueError:使用序列设置数组元素

x_input 和 x_reconstruct 都是 [m, n, 1] np 数组。最后一行代码其实是直接从 Keras 内置的 MSE 损失函数中复制过来的。

另外,我认为损失是按样本计算的。如果输入和重构输入的维度都是 [m, n, 1],那么 Keras 内置损失的结果也将是一个大小为 [m, n] 的矩阵。那么为什么它可以正常工作呢?

然后我尝试直接通过我们np的功能

    def MyLoss(self, x_input, x_reconstruct):        
        a = np.copy(x_reconstruct)
        a = np.asarray(a, dtype=self.precision)       
        a = np.floor(4*a)/4
        Diff = a - x_input
        xx = np.mean(np.square(Diff), axis=-1)
        yy = np.sum(xx)
        return yy

但错误仍然存​​在。我犯了什么错误?代码应该怎么写?

借用Make a Custom loss function in Keras in detail的建议,我尝试关注

    def MyLoss(self, x_input, x_reconstruct):    
        if self.precision == 'float16':
            K.set_floatx('float16')
            K.set_epsilon(1e-4)
        a = K.cast_to_floatx(x_input)
        a = K.round(a*4.-0.5)/4.0
        return K.sum(K.mean(K.square(x_input-a), axis=-1))

但同样的错误发生

【问题讨论】:

  • 两个帮助调试的建议: 1) 在 return 语句之前插入一行,print("got here"),这样您就可以验证问题出在最后一行的计算上; 2)输出x_input.shape和a.shape看是否兼容。
  • 恐怕不行。当我调用model.compile(loss=self.MyLoss, optimizer= CurOptimizer, metrics=CurMetrics) 时,甚至在代码到达那里之前就发生了错误

标签: keras loss-function


【解决方案1】:

你不能在你的损失中使用numpy 数组。您必须使用TensorFlowKeras 后端操作。试试这个吧:

import tensorflow as tf
import keras.backend as K

def MyLoss(x_input, x_reconstruct):
    a = tf.cast(x_input, dtype='tf.float16')       
    a = tf.floor(4*a)/4
    return K.mean(K.square(a - x_input), axis=-1)

【讨论】:

    【解决方案2】:

    我自己找到了答案,在这里分享一下

    如果我写这样的代码

        def MyLoss(self, y_true, y_pred):    
            if self.precision == 'float16':
                K.set_floatx('float16')
                K.set_epsilon(1e-4)
            return K.mean(K.square(y_true-K.round(y_pred*4.-0.5)/4.0), axis=-1)
    

    有效。我认为,诀窍是我不能使用“K.cast_to_floatx(y_true)”。相反,只需直接使用 y_true 即可。我还是不明白为什么……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-10
      • 2017-12-20
      • 2019-11-09
      • 1970-01-01
      • 2020-03-02
      • 2021-03-09
      • 2021-02-24
      • 1970-01-01
      相关资源
      最近更新 更多