【问题标题】:Tensorflow2: How to print value of a tensor returned from tf.function when eager execution is disabled?Tensorflow2:当急切执行被禁用时,如何打印从 tf.function 返回的张量的值?
【发布时间】:2021-08-17 07:24:17
【问题描述】:

我读到我可以通过在 tf.function 定义中使用 tf.print 来查看 tf 变量的内容。它不起作用。我的__tf.version__ 是 2.5.0。我在 Jupyter notebook 中运行以下函数:

tf.compat.v1.disable_eager_execution()

@tf.function
def tf_fun(inputs):
    x = tf.strings.lower(inputs)
    tf.print(x)
    return x
  • 不打印
tf_fun(inputs)
<tf.Tensor 'StatefulPartitionedCall_6:0' shape=(7,) dtype=string>
  • 带打印
print(tf_fun(inputs))
Tensor("StatefulPartitionedCall_5:0", shape=(7,), dtype=string)

我希望禁用急切执行,因为我使用了 tf.Transform 模块中的一些函数,这些函数仅在此笔记本中其他地方的图形模式下工作。 如何查看张量的内容以确保我的函数完全符合我的要求?

另一个问题(不太重要)是,如果我尝试将返回值分配给变量以进行进一步处理,tf.print 只有在第一次调用tf_fun 时才会打印任何内容(我知道它与跟踪有关,但我不明白它,想知道如何解决它。)

编辑:从tf.Transorm 模块添加内容后出现错误。

@tf.function
def transform_product1(inputs, top_k_products):
    product = tf.strings.lower(inputs)
    product = tf.strings.reduce_join(product, -1, separator = ' ')
    product = tft.vocabulary(product, top_k= 4)
    return product

prod = transform_product1(inputs,4)
sess = tf.compat.v1.Session() 
print(sess.run(prod))
InvalidArgumentError: You must feed a value for placeholder tensor 'PartitionedCall_7/vocabulary/temporary_analyzer_output_1/Placeholder' with dtype string
     [[{{node vocabulary/temporary_analyzer_output_1/Placeholder}}]]

【问题讨论】:

  • 禁用急切执行后,您需要运行会话来触发图形。像这样:a=tf_fun(inputs) sess=tf.compat.v1.Session() print(sess.run(a))。在不禁用 Eager-mode 的情况下,只需使用 @tf.function 装饰器,您就可以毫无问题地使用 tf.print
  • @Kaveh 谢谢!不幸的是,我还有其他问题 - 我在编辑中描述了它们

标签: python tensorflow tensorflow2.0 tensor eager-execution


【解决方案1】:

您也可以尝试force_tf_compat_v1=True 运行旧版tf.Transform,并尝试通过在tf.function 之外调用函数来打印函数的返回值。 或者对于您使用 tf.transform 的部分,您可以使用tf.Graph 将其包装,如下所示。

g = tf.Graph()
with g.as_default():
  # Define operations and tensors in `g`.
  c = tf.constant(30.0)

【讨论】:

    猜你喜欢
    • 2023-01-11
    • 2019-04-25
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    相关资源
    最近更新 更多