【发布时间】: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