【问题标题】:Custom Objective Function Keras自定义目标函数 Keras
【发布时间】:2017-12-23 17:57:39
【问题描述】:

我需要定义自己的损失函数,我使用的是 GAN 模型,我的损失将包括真实图像和生成图像之间的逆向损失和 L1 损失。

我试图写一个函数但是出现以下错误:

ValueError: ('Could not interpret loss function identifier:', Elemwise{add,no_inplace}.0)

我的损失函数是:

def loss_function(y_true, y_pred, y_true1, y_pred1):

    bce=0
    for i in range (64):
        a = y_pred1[i]        
        b = y_true1[i]        
        x = K.log(a)
        bce=bce-x
    bce/=64
    print('bce = ', bce)

    for i in zip( y_pred, y_true):
        img   = i[0]
        image = np.zeros((64,64),dtype=y_pred.dtype)
        image = img[0,:,:]                
        image = image*127.5+127.5                
        imgfinal = Image.fromarray(image.astype(np.uint8))

        img1 = i[1]
        image1 = np.zeros((64,64), dtype=y_true.dtype)
        image1 = img1[0,:,:]
        image1 = image1*127.5+127.5              
        imgfinal1 = Image.fromarray(image1.astype(np.uint8))

        diff = ImageChops.difference(imgfinal,imgfinal1)
        h = diff.histogram()
        sq = (value*((idx%256)**2) for idx, value in enumerate(h))       
        sum_of_squares = sum(sq)
        lossr = math.sqrt(sum_of_squares/float(im1.size[0] * im1.size[1]))
        loss  = loss+lossr

    loss /=(64*127) 
    print('loss = ', loss)

    return x+loss

【问题讨论】:

  • 你能把错误追溯到抛出它的那一行吗?
  • discriminator_on_generator.compile(loss = loss_function(y_true ,y_pred ,y_true1 ,y_pred1), optimizer=g_optim) - 这是抛出错误的行,这是我调用这个 loss_function 的地方。跨度>
  • 您能否追踪到错误源自您的自定义损失函数内部的哪一行?
  • 错误不是源自损失函数内部,但 keras 无法识别我的损失函数。
  • 根据您的评论,我添加了一个答案,这也将有助于包含您在答案中提到的那行代码...我要编辑所以

标签: python machine-learning keras loss-function


【解决方案1】:

根据您的评论,您说您将自定义函数传递给编译操作,如下所示:

discriminator_on_generator.compile(loss = loss_function(y_true ,y_pred ,y_true1 ,y_pred1), optimizer=g_optim)

但是,根据docs,您应该传递您的自定义函数,例如:

discriminator_on_generator.compile(loss = loss_function, optimizer=g_optim)

您可以查看这个 github discussion,其中还指出了如何使用自定义损失函数。

注意:由于您的函数中需要 4 个参数,并且预计最多只有 2 个,您可以按照此 github issue 中的建议进行操作,其中涉及定义容器函数处理这些额外参数,例如:

def loss_function(y_true1, y_pred1):
    def my_nested_function(y_true, y_pred):
        #now you can work with all 4 variables here

并在编译时将其作为参数传递:

discriminator_on_generator.compile(loss=loss_function(y_true1, y_pred1), optimizer=g_optim)

或者,您可以将 4 个参数合并为 2 个(y_true、y_predict),然后在单个函数中将它们拆分为 4 个变量(y_true、y_pred、y_true1、y_predict1),因为它们也在那个问题上讨论。

【讨论】:

  • 我已经尝试过了,它给出了错误:- 给定损失函数的两个论点,而四个是必需的。因为默认损失函数只需要两个参数 y_true 和 y_pred。
  • 编辑我的问题以展示您如何处理它
  • 谢谢,我也在尝试这样的事情。
  • 好的,让我知道它是否有效。似乎通过按照我指示的方式调用函数解决了您的原始问题(函数无法识别),因为现在您遇到了一个新错误。我添加的编辑应该可以解决您的 new 问题。如果这些新问题仍然存在,请告诉我或考虑询问/搜索其他问题
  • 我试过了,但还是出现了同样的错误,我认为是因为我的函数不在theano或tensorflow中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-15
  • 2016-02-24
  • 2016-11-12
  • 1970-01-01
  • 2020-12-19
  • 2017-12-18
  • 2020-03-27
相关资源
最近更新 更多