获取损失函数中张量的值

Get values of tensors in loss function

我想得到 y_predy_true 张量的值 keras backend function。我需要它能够执行一些自定义计算并更改损失,这些计算仅适用于实际数组值。

def mean_squared_error(y_true, y_pred):
    #some code here
    return K.mean(K.square(y_pred - y_true), axis=-1)

keras 有办法做到这一点吗?或者在任何其他 ML 框架(tf、pytorch、theano)中?

不,通常你不能那样计算损失,因为 Keras 基于自动微分的框架(如 Theano、TensorFlow),它们需要知道你在两者之间进行了哪些操作,以便计算损失的梯度。

您需要使用 keras.backend 函数来实现损失计算,否则无法计算梯度,也无法进行优化。

尝试将其包含在损失函数中: y_true = keras.backend.print_tensor(y_true, 消息='y_true')

以下是 Keras 文档 (https://keras.io/backend/) 的摘录:

print_tensor keras.backend.print_tensor(x, 消息='') 评估时打印消息和张量值。

注意 print_tensor returns 一个与 x 相同的新张量,应该在代码的后面部分使用。否则,评估时不考虑打印操作。