Keras中基于输入数据的自定义损失函数 [英] Custom loss function in Keras based on the input data

查看:40
本文介绍了Keras中基于输入数据的自定义损失函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Keras 创建自定义损失函数.我想根据输入计算损失函数并预测神经网络的输出.

I am trying to create the custom loss function using Keras. I want to compute the loss function based on the input and predicted the output of the neural network.

我尝试在 Keras 中使用 customloss 函数.我认为 y_true 是我们为训练提供的输出,而 y_pred 是神经网络的预测输出.下面的损失函数与 Keras 中的mean_squared_error"损失相同.

I tried using the customloss function in Keras. I think y_true is the output that we give for training and y_pred is the predicted output of the neural network. The below loss function is same as "mean_squared_error" loss in Keras.

def customloss(y_true, y_pred):
    return K.mean(K.square(y_pred - y_true), axis=-1)

除了 mean_squared_error 损失之外,我还想使用神经网络的输入来计算自定义损失函数.有没有办法将输入发送到神经网络作为 customloss 函数的参数.

I would like to use the input to the neural network also to compute the custom loss function in addition to mean_squared_error loss. Is there a way to send an input to the neural network as an argument to the customloss function.

谢谢.

推荐答案

针对您提出的问题,我遇到了 2 个解决方案.

I have come across 2 solutions to the question you asked.

  1. 您可以将输入张量作为参数传递给自定义损失包装函数.

    def custom_loss(i):

        def loss(y_true, y_pred):
            return K.mean(K.square(y_pred - y_true), axis=-1) + something with i...
        return loss

    def baseline_model():
        # create model
        i = Input(shape=(5,))
        x = Dense(5, kernel_initializer='glorot_uniform', activation='linear')(i)
        o = Dense(1, kernel_initializer='normal', activation='linear')(x)
        model = Model(i, o)
        model.compile(loss=custom_loss(i), optimizer=Adam(lr=0.0005))
        return model

此处接受的答案中也提到了此解决方案

  1. 您可以使用来自输入的额外数据列填充标签并编写自定义损失.如果您只想要输入中的一个/几个特征列,这会很有帮助.

    def custom_loss(data, y_pred):

        y_true = data[:, 0]
        i = data[:, 1]
        return K.mean(K.square(y_pred - y_true), axis=-1) + something with i...


    def baseline_model():
        # create model
        i = Input(shape=(5,))
        x = Dense(5, kernel_initializer='glorot_uniform', activation='linear')(i)
        o = Dense(1, kernel_initializer='normal', activation='linear')(x)
        model = Model(i, o)
        model.compile(loss=custom_loss, optimizer=Adam(lr=0.0005))
        return model


    model.fit(X, np.append(Y_true, X[:, 0], axis =1), batch_size = batch_size, epochs=90, shuffle=True, verbose=1)

也可以在此线程中找到此解决方案.

This solution can be found also here in this thread.

当我不得不在损失中使用输入特征列时,我只使用了第二种方法.我使用了带有标量参数的第一种方法;但我相信张量输入也有效.

I have only used the 2nd method when I had to use input feature columns in the loss. I have used the first method with scalar arguments; but I believe a tensor input works as well.

这篇关于Keras中基于输入数据的自定义损失函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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