【问题标题】:Custom loss/objective function with additional variable input in KerasKeras 中带有附加变量输入的自定义损失/目标函数
【发布时间】:2018-08-26 23:17:48
【问题描述】:

我正在尝试在 Keras(张量流后端)中创建一个自定义目标函数,其中包含一个附加参数,其值取决于正在训练的批次。

例如:

def myLoss(self, stateValues):
    def sparse_loss(y_true, y_pred):
        foo = tf.nn.softmax_cross_entropy_with_logits(labels=y_true, logits=y_pred)
        return tf.reduce_mean(foo * stateValues)
    return sparse_loss


self.model.compile(loss=self.myLoss(stateValue = self.stateValue),
        optimizer=Adam(lr=self.alpha))

我的火车功能如下

for batch in batches:
    self.stateValue = computeStateValueVectorForCurrentBatch(batch)
    model.fit(xVals, yVals, batch_size=<num>)

但是,损失函数中的 stateValue 并没有被更新。它只是使用 stateValue 在 model.compile 步骤中的值。

我想这可以通过将 placeHolder 用于 stateValue 来解决,但我不知道该怎么做。有人可以帮忙吗?

【问题讨论】:

    标签: tensorflow keras loss-function objective-function


    【解决方案1】:

    您的损失函数没有得到更新,因为 keras 没有在每批之后编译模型,因此没有使用更新的损失函数。

    您可以定义一个自定义回调,该回调将在每批之后更新损失值。像这样的:

    from keras.callbacks import Callback
    
    class UpdateLoss(Callback):
        def on_batch_end(self, batch, logs={}):
            # I am not sure what is the type of the argument you are passing for computing stateValue ??
            stateValue = computeStateValueVectorForCurrentBatch(batch)
            self.model.loss = myLoss(stateValue)
    

    【讨论】:

      猜你喜欢
      • 2021-07-28
      • 2020-10-05
      • 2021-05-23
      • 2021-05-04
      • 2019-08-22
      • 2020-03-02
      • 2020-12-19
      • 2017-12-18
      • 2020-03-27
      相关资源
      最近更新 更多