建立自定义损失函数时的错误 [英] Errors when Building up a Custom Loss Function

查看:99
本文介绍了建立自定义损失函数时的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to build up my own loss function as follows

    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:设置具有序列的数组元素

In compilation, it says ValueError: setting an array element with a sequence

x_input和x_reconstruct都是[m,n,1]个np数组.实际上,最后一行代码是直接从Keras的内置MSE损失函数复制的.

Both x_input and x_reconstruct are [m, n, 1] np arrays. The last line of code is actually copied directly from Keras' built-in MSE loss function.

我还假设每个样本都计算出损失.如果输入和重构输入的尺寸均为[m,n,1],则Keras内置损耗的结果也将是矩阵大小[m,n].那么为什么它可以正常工作?

Also, I suppose loss is calculated per sample. If dimensions of the input and reconstructed input are both [m, n, 1], the result of Keras' built-in loss will also be a matrix sized [m, n]. So why does it work properly?

然后我尝试直接使用np的功能

I then tried to us np's functions directly by

    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

但是错误仍然存​​在.我犯了什么错误?应该如何编写代码?

yet the error persists. What mistake did I make? How should write the code?

曾从在详细介绍Keras ,我尝试了以下

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

但是发生同样的错误

推荐答案

您不能在丢失中使用numpy数组.您必须使用TensorFlowKeras后端操作.试试这个吧:

You can not use numpy arrays in your loss. You have to use TensorFlow or Keras backend operations. Try this maybe:

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)

这篇关于建立自定义损失函数时的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆