【问题标题】:Keras custom loss function not printing value of tensorKeras自定义损失函数不打印张量的值
【发布时间】:2019-07-28 02:38:54
【问题描述】:

我只是在写一个简单的损失函数,我必须将张量转换为 numpy 数组(这是必不可少的)。我只是想打印张量的值,但我收到了这个错误:-

Tensor("loss/activation_4_loss/Print:0", shape=(?, 224, 224, 2), dtype=float32)

def Lc(y_true, y_pred):
    x=K.print_tensor(y_pred)
    print(x)
    return K.mean(y_pred)

请告诉我如何从张量中获取值(数字)?我也尝试了“eval”,但它也抛出了一个很大的错误,即没有会话,它是一个占位符等。整个程序执行良好,只是“print_tensor”行引起了问题。

【问题讨论】:

  • K.print_tensor() 似乎返回了一个 Print Tensor 对象。只需遵循基本步骤:print( tf.Session().run(x) )
  • 另外,如有必要,您可以在 TensorFlow 中启用 Eager 模式,以便打印张量的值。
  • 您的前提是错误的,如果您使用 numpy 作为其中的一部分,Keras 中的损失函数将不起作用,因为无法通过 numpy 代码传播梯度。
  • @ShubhamPanchal 我收到错误,你必须在 keras 自定义损失中执行 tf.session().run(x) 时提供值。

标签: python tensorflow keras loss-function


【解决方案1】:

打印语句是多余的。 print_tensor 已经打印了这些值。

来自 print_tensor 的文档:

"注意print_tensor 返回一个与x 相同的新张量 应在以下代码中使用。否则 评估期间不考虑打印操作。”

在上面的代码中,由于 y_pred 被赋值给 x 并且 x 不再被使用,所以打印失败。

使用以下版本。

def Lc(y_true, y_pred):
    y_pred=K.print_tensor(y_pred)
    return K.mean(y_pred)

def cat_loss(y_true, y_pred):
    y_pred = K.print_tensor(y_pred)
    return K.categorical_crossentropy(y_true, y_pred)

将这个 cat_loss 函数放入训练循环后,我可以看到如下输出:

[[0.000191014129 0.230871275 0.43813318]...]

190/255 [======================>........] - ETA:0s - 损失:0.3442 - acc:0.9015

[[3.16367514e-05 1.70419597e-07 0.000147014405]...]

【讨论】:

    猜你喜欢
    • 2020-01-08
    • 2021-01-03
    • 2021-02-08
    • 2020-05-30
    • 2020-12-19
    • 2017-12-18
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多