建立自定义损失函数时的错误

时间:2019-06-14 03:59:38

标签: keras loss-function

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

    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))

但是发生同样的错误

2 个答案:

答案 0 :(得分:3)

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

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)

答案 1 :(得分:1)

我自己找到了答案,然后让我在这里分享

如果我写这样的代码

    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即可。我仍然不明白为什么...

相关问题