【问题标题】:How to print a tensor's value inside tf.while_loop without returning it?如何在 tf.while_loop 中打印张量的值而不返回它?
【发布时间】:2018-10-28 16:39:40
【问题描述】:

我想要的是在 tf.while_loop 体内打印张量的值而不返回张量,但仍使用计算图。下面我有一些简单的例子来解释我想要成功以及到目前为止我所做的事情。

方法1(有效):

TF 通过将 tf.Print 操作引入图形来支持在评估模型时打印张量的选项,但这需要从主体返回张量:

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, [1])

def body(x):
    a = tf.constant( np.array([2]) , dtype=tf.float32)
    x = a + x
    x = tf.Print(x,[x], summarize=100) <= print here (works)
    return x

def condition(x):
    return tf.reduce_sum(x) < 10

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    result = tf.while_loop(cond=condition, body=body, loop_vars=[x])
    result_out = sess.run([result], feed_dict={ x : np.zeros(1)})
    print(result_out)

出来:

[2]
[4]
[6]
[8] 
[10]
[array([10.], dtype=float32)] 

方法2(有效):

TF 支持在不使用 Eager 模式创建计算图的情况下打印张量的选项。下面同样的例子:

import tensorflow as tf
import numpy as np

tf.enable_eager_execution()

def body(x):
    a = tf.constant(np.array([2]), dtype=tf.int32)
    x = a + x
    print(x) <= print here (works)
    return x

def cond(x):
    return tf.reduce_sum(x) < 10 # sum over an axis

x = tf.constant(0, shape=[1])

#result = tf.while_loop(cond=condition, body=body, loop_vars=(x,0))
result=tf.while_loop(cond, body, [x])
print(result)

出来:

tf.Tensor([2], shape=(1,), dtype=int32)
tf.Tensor([4], shape=(1,), dtype=int32)
tf.Tensor([6], shape=(1,), dtype=int32)
tf.Tensor([8], shape=(1,), dtype=int32)

tf.Tensor([10], shape=(1,), dtype=int32)
tf.Tensor([10], shape=(1,), dtype=int32) 

方法3(失败):

我想要的是在图形环境中使用急切执行来打印张量(如所述:here)。

import tensorflow as tf
import numpy as np

tfe = tf.contrib.eager

x = tf.placeholder(tf.int32, [1])

def my_py_func(x):
  print(x)  # It's eager!

def body(x):
    a = tf.constant( np.array([2]) , dtype=tf.int32)
    x = a + x
    tfe.py_func(my_py_func, x, tf.int32) <= print here (does not work)
    return x

def condition(x):
    return tf.reduce_sum(x) < 10

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    result = tf.while_loop(condition, body, [x])
    result_out = sess.run([result], feed_dict={ x : np.zeros(1)} )
    print(result_out)

出来:

TypeError: Expected list for 'input' argument to 'EagerPyFunc' Op, not Tensor("while/add:0", shape=(1,), dtype=int32).

当然在这个例子中我从正文返回张量x,但我想在循环内打印!

【问题讨论】:

  • 为什么第一种方法不行?如果您执行x = tf.Print(x, [a], summarize=100),您将打印张量a 的值而不返回此张量。
  • 我认为 tf.Print 仅用于打印返回的张量。非常感谢它有效。您可以将其发布为我接受的答案吗?

标签: python tensorflow printing while-loop tensor


【解决方案1】:

在第一种方法中,您可以打印张量的值而不返回它。例如:

x = tf.Print(x, [a])

在这种情况下,tf.Print 是一个恒等运算,其副作用是在评估时打印张量 a 的值。

【讨论】:

    猜你喜欢
    • 2016-09-23
    • 1970-01-01
    • 2021-12-16
    • 2023-01-11
    • 2017-09-12
    • 2016-09-01
    • 2017-11-10
    • 2018-06-26
    相关资源
    最近更新 更多