gpt4 book ai didi

python - Keras:平均不同的损失函数

转载 作者:行者123 更新时间:2023-12-01 09:25:31 25 4
gpt4 key购买 nike

我正在使用带有 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')

最佳答案

您正在 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

关于python - Keras:平均不同的损失函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50437579/

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