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

查看:408
本文介绍了基于输入数据的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天全站免登陆