2

我需要定义自己的损失函数,我使用的是 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
4

1 回答 1

4

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

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

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

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

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

注意:由于您的函数中需要 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),正如他们在该问题中所讨论的那样。

于 2017-07-19T15:40:30.190 回答