gpt4 book ai didi

keras - Keras 中基于输入数据的自定义损失函数

转载 作者:行者123 更新时间:2023-12-04 11:13:25 29 4
gpt4 key购买 nike

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

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

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

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

谢谢你。

最佳答案

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

  • 您可以将输入张量作为参数传递给自定义损失包装函数。
  •     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

    the accepted answer here中也提到了这个解决方案
  • 您可以使用来自输入的额外数据列填充标签并编写自定义损失。如果您只想要输入中的一个/几个特征列,这将很有帮助。
  •     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)

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

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

    关于keras - Keras 中基于输入数据的自定义损失函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55445712/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com