【问题标题】:Keras Model - Get input in custom loss functionKeras 模型 - 在自定义损失函数中获取输入
【发布时间】:2020-05-12 20:54:25
【问题描述】:

我在使用 Keras 自定义损失函数时遇到问题。我希望能够以 numpy 数组的形式访问 truth。 因为它是一个回调函数,我想我不是在急切执行,这意味着我无法使用 backend.get_value() 函数访问它。我也尝试了不同的方法,但它总是回到这个“张量”对象不存在的事实。

我需要在自定义损失函数中创建会话吗?

我使用的是最新的 Tensorflow 2.2。

def custom_loss(y_true, y_pred):

    # 4D array that has the label (0) and a multiplier input dependant
    truth = backend.get_value(y_true)

    loss = backend.square((y_pred - truth[:,:,0]) * truth[:,:,1])
    loss = backend.mean(loss, axis=-1)  

    return loss

 model.compile(loss=custom_loss, optimizer='Adam')
 model.fit(X, np.stack(labels, X[:, 0], axis=3), batch_size = 16)


我希望能够接触到真相。它有两个组件(标签、乘数,每个项目都不同。我看到了一个依赖于输入的解决方案,但我不确定如何访问该值。Custom loss function in Keras based on the input data

【问题讨论】:

  • 你想对自定义损失函数里面的numpy数组做什么?你不会在那里对truth 做任何事情。 weight_buildingweight_space 实际上在做什么?你能告诉我们你是如何编译模型的吗?如果删除 truth=backend.get_value(y_true),是否会收到错误消息?
  • 我对其进行了简化和编辑。

标签: tensorflow keras


【解决方案1】:

我认为您可以通过在model.compile 中启用run_eagerly=True 来做到这一点,如下所示。

model.compile(loss=custom_loss(weight_building, weight_space),optimizer=keras.optimizers.Adam(), metrics=['accuracy'],run_eagerly=True)

我认为您还需要更新custom_loss,如下所示。

def custom_loss(weight_building, weight_space):
  def loss(y_true, y_pred):
    truth = backend.get_value(y_true)
    error = backend.square((y_pred - y_true))
    mse_error = backend.mean(error, axis=-1) 
    return mse_error
  return loss

我用一个简单的mnist 数据来演示这个想法。请看代码here

【讨论】:

  • 这对我来说似乎是一个很好的答案。一些提示:(a)我们更喜欢这里的帖子而不是要求接受/赞成。如果材料好,它将有机地获得选票。可以添加评论来解释如何使用投票/接受系统,或者如果有人忘记了,可以温和地提醒,但要放轻松。 (b) 不需要添加评论邀请,读者应该知道这一点。如果可以的话,让你的材料保持简洁——这也能让未来的读者读起来更好看。
  • 感谢@halfer 的编辑和建议。从现在开始将遵循。
  • 这是我所期待的
猜你喜欢
  • 2021-03-20
  • 2021-05-23
  • 2020-12-19
  • 2017-12-18
  • 2020-03-27
  • 1970-01-01
  • 2019-08-22
  • 2020-03-02
  • 2018-10-28
相关资源
最近更新 更多