【问题标题】:Keras: averaging different loss functionsKeras:平均不同的损失函数
【发布时间】:2018-05-20 17:28:16
【问题描述】:

我正在使用带有 TensorFlow 后端的 Keras,并且想定义一个自定义损失函数,如下所示:

  • 它计算 y_true 和 y_pred 的前 2 个条目之间的欧几里德距离
  • 它计算其余条目之间的绝对误差

然后取平均值。

我这样做:

def custom_objective(y_true, y_pred):
    y_true = backend.get_value(y_true)
    y_pred = backend.get_value(y_pred)

    a = np.sqrt(np.mean(np.square(y_pred[:2] - y_true[:2]), axis=-1))
    b = np.sum(np.abs(y_true[2:] - y_pred[2:]))
    return (a + b) / 5

我在编译模型时得到一个InvalidArgumentError

model.compile(loss=custom_objective, optimizer='adam')

【问题讨论】:

  • 你不能使用 numpy 作为定义 Keras 模型的一部分。

标签: python tensorflow keras


【解决方案1】:

您在 Keras 张量上使用 NumPy,不幸的是,这是一个致命的组合。您正在寻找的内容类似于:

def custom_objective(y_true, y_pred):
  a = K.sqrt(K.mean(K.square(y_pred[:2] - y_true[:2]), axis=-1))
  b = K.sum(K.abs(y_true[2:] - y_pred[2:]))
  return (a + b) / 5 # these operators work on tensors

【讨论】:

  • 张量 y_predy_true 在 Keras 中通常有 2 个维度。请改用y_true[:, :2]y_pred[:, :2]
猜你喜欢
  • 2019-11-28
  • 2018-04-03
  • 2022-10-19
  • 2019-02-06
  • 2020-09-11
  • 2019-05-23
  • 1970-01-01
  • 2019-12-04
  • 2018-09-10
相关资源
最近更新 更多