如何将TensorFlow tf.print与非大写p一起使用?

Cod*_*key 5 python keras tensorflow

我在自定义损失函数中有一些TensorFlow代码。

我正在使用 tf.Print(node, [debug1, debug2], "print my debugs: ")

它工作正常,但TF说tf.Print是被描述的,一旦我更新TensorFlow并且我应该使用`` tf.**p**rint()p'' 小将被删除。

我尝试使用tf.print与我相同的方式,tf.Print()但无法正常工作。一旦我在Keras中安装了模型,就会出现错误。不像tf.Printtf.print似乎可以吸收任何东西**kwargs,那么我应该给它什么呢?与tf.Print它不同的是,似乎没有返回我可以注入到计算图中的内容。

确实很难搜索,因为所有在线信息都与有关tf.Print()

有人可以解释如何使用tf.print()吗?

编辑:示例代码

def custom_loss(y_true, y_pred):
    loss = K.mean(...)
    print_no_op = tf.Print(loss, [loss, y_true, y_true.shape], "Debug output: ")
    return print_no_op

model.compile(loss=custom_loss)
Run Code Online (Sandbox Code Playgroud)

jde*_*esa 7

的文档tf.printtf.Print提及都tf.print返回一个没有输出的操作,因此它不能被评估为任何值。的语法tf.print更类似于 Python 的 builtin print。在您的情况下,您可以按如下方式使用它:

def custom_loss(y_true, y_pred):
    loss = K.mean(...)
    print_op = tf.print("Debug output:", loss, y_true, y_true.shape)
    with tf.control_dependencies([print_op]):
        return K.identity(loss)
Run Code Online (Sandbox Code Playgroud)

这里K.identity创建一个新的张量,与 相同loss但具有对 的控制依赖性print_op,因此评估它将强制执行打印操作。请注意,Keras 也提供了K.print_tensor,尽管它不如tf.print.

  • 这里有很好的讨论:https://github.com/tensorflow/community/pull/14/files。似乎 tf.print 是为了急于执行而创建的,而这给图形执行带来的痛苦只是成本。据推测,一旦处于图形模式,您就不需要打印语句。 (2认同)