Python 如何在 TensorFlow 中打印 Tensor 对象的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33633370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print the value of a Tensor object in TensorFlow?
提问by Dawny33
I have been using the introductory example of matrix multiplication in TensorFlow.
我一直在使用 TensorFlow 中矩阵乘法的介绍性示例。
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
When I print the product, it is displaying it as a Tensor
object:
当我打印产品时,它将它显示为一个Tensor
对象:
<tensorflow.python.framework.ops.Tensor object at 0x10470fcd0>
But how do I know the value of product
?
但是我怎么知道 的价值product
呢?
The following doesn't help:
以下没有帮助:
print product
Tensor("MatMul:0", shape=TensorShape([Dimension(1), Dimension(1)]), dtype=float32)
I know that graphs run on Sessions
, but isn't there any way I can check the output of a Tensor
object without running the graph in a session
?
我知道图形在 上运行Sessions
,但是没有任何方法可以在Tensor
不运行图形的情况下检查对象的输出session
吗?
采纳答案by mrry
The easiest[A]way to evaluate the actual value of a Tensor
object is to pass it to the Session.run()
method, or call Tensor.eval()
when you have a default session (i.e. in a with tf.Session():
block, or see below). In general[B], you cannot print the value of a tensor without running some code in a session.
评估对象实际值的最简单[A]方法Tensor
是将其传递给Session.run()
方法,或Tensor.eval()
在您有默认会话时调用(即在with tf.Session():
块中,或见下文)。通常[B],如果不在会话中运行某些代码,则无法打印张量的值。
If you are experimenting with the programming model, and want an easy way to evaluate tensors, the tf.InteractiveSession
lets you open a session at the start of your program, and then use that session for all Tensor.eval()
(and Operation.run()
) calls. This can be easier in an interactive setting, such as the shell or an IPython notebook, when it's tedious to pass around a Session
object everywhere. For example, the following works in a Jupyter notebook:
如果您正在试验编程模型,并且想要一种简单的方法来评估张量,那么tf.InteractiveSession
您可以在程序开始时打开一个会话,然后将该会话用于所有Tensor.eval()
(和Operation.run()
)调用。这在交互式设置中会更容易,例如 shell 或 IPython notebook,当Session
到处传递对象很乏味时。例如,以下内容适用于 Jupyter 笔记本:
with tf.Session() as sess: print(product.eval())
This might seem silly for such a small expression, but one of the key ideas in Tensorflow 1.x is deferred execution: it's very cheap to build a large and complex expression, and when you want to evaluate it, the back-end (to which you connect with a Session
) is able to schedule its execution more efficiently (e.g. executing independent parts in parallel and using GPUs).
对于这么小的表达式来说,这可能看起来很愚蠢,但是 Tensorflow 1.x 中的一个关键思想是延迟执行:构建一个大而复杂的表达式非常便宜,并且当您想要评估它时,后端(以与 a 连接的Session
) 能够更有效地安排其执行(例如并行执行独立部分和使用 GPU)。
[A]: To print the value of a tensor without returning it to your Python program, you can use the tf.print()
operator, as Andrzej suggests in another answer. According to the official documentation:
[A]:要打印张量的值而不将其返回到 Python 程序,您可以使用tf.print()
运算符,正如Andrzej 在另一个答案中建议的那样。根据官方文档:
To make sure the operator runs, users need to pass the produced op to
tf.compat.v1.Session
's run method, or to use the op as a control dependency for executed ops by specifying withtf.compat.v1.control_dependencies([print_op]
), which is printed to standard output.
为确保操作符运行,用户需要将生成的 op 传递给
tf.compat.v1.Session
的 run 方法,或者通过指定 withtf.compat.v1.control_dependencies([print_op]
)将 op 作为执行的 ops 的控制依赖项,将其打印到标准输出。
Also note that:
另请注意:
In Jupyter notebooks and colabs,
tf.print
prints to the notebook cell outputs. It will not write to the notebook kernel's console logs.
在 Jupyter 笔记本和 colab 中,
tf.print
打印到笔记本单元输出。它不会写入笔记本内核的控制台日志。
[B]: You mightbe able to use the tf.get_static_value()
function to get the constant value of the given tensor if its value is efficiently calculable.
[B]:如果给定张量的值是可有效计算的,您也许可以使用该tf.get_static_value()
函数来获取其常数值。
回答by Salvador Dali
No, you can not see the content of the tensor without running the graph (doing session.run()
). The only things you can see are:
不,如果不运行图形(执行session.run()
),您就无法看到张量的内容。你能看到的只有:
- the dimensionality of the tensor (but I assume it is not hard to calculate it for the list of the operationsthat TF has)
- type of the operation that will be used to generate the tensor (
transpose_1:0
,random_uniform:0
) - type of elements in the tensor (
float32
)
- 张量的维数(但我认为对于TF的操作列表计算它并不难)
- 将用于生成张量 (
transpose_1:0
,random_uniform:0
)的操作类型 - 张量中的元素类型 (
float32
)
I have not found this in documentation, but I believe that the values of the variables (and some of the constants are not calculated at the time of assignment).
我没有在文档中找到这个,但我相信变量的值(和一些常量在赋值时没有计算)。
Take a look at this example:
看看这个例子:
import tensorflow as tf
from datetime import datetime
dim = 7000
The first example where I just initiate a constant Tensor of random numbers run approximately the same time irrespectibly of dim (0:00:00.003261
)
第一个例子,我只是启动一个随机数的常数张量,几乎与dim ( 0:00:00.003261
) 的运行时间大致相同
startTime = datetime.now()
m1 = tf.truncated_normal([dim, dim], mean=0.0, stddev=0.02, dtype=tf.float32, seed=1)
print datetime.now() - startTime
In the second case, where the constant is actually gets evaluated and the values are assigned, the time clearly depends on dim (0:00:01.244642
)
在第二种情况下,实际计算常量并分配值,时间显然取决于dim ( 0:00:01.244642
)
startTime = datetime.now()
m1 = tf.truncated_normal([dim, dim], mean=0.0, stddev=0.02, dtype=tf.float32, seed=1)
sess = tf.Session()
sess.run(m1)
print datetime.now() - startTime
And you can make it more clear by calculating something (d = tf.matrix_determinant(m1)
, keeping in mind that the time will run in O(dim^2.8)
)
你可以通过计算一些东西来让它更清楚(d = tf.matrix_determinant(m1)
记住时间会过去O(dim^2.8)
)
P.S. I found were it is explained in documentation:
PS我发现它在文档中有解释:
A Tensor object is a symbolic handle to the result of an operation, but does not actually hold the values of the operation's output.
Tensor 对象是操作结果的符号句柄,但实际上并不保存操作输出的值。
回答by Andrzej Pronobis
While other answers are correct that you cannot print the value until you evaluate the graph, they do not talk about one easy way of actually printing a value inside the graph, once you evaluate it.
虽然其他答案是正确的,在您评估图形之前您无法打印该值,但他们并没有讨论一种在评估图形后实际打印值的简单方法。
The easiest way to see a value of a tensor whenever the graph is evaluated (using run
or eval
) is to use the Print
operation as in this example:
在计算图时(使用run
或eval
)查看张量值的最简单方法是使用Print
本示例中的操作:
# Initialize session
import tensorflow as tf
sess = tf.InteractiveSession()
# Some tensor we want to print the value of
a = tf.constant([1.0, 3.0])
# Add print operation
a = tf.Print(a, [a], message="This is a: ")
# Add more elements of the graph using a
b = tf.add(a, a)
Now, whenever we evaluate the whole graph, e.g. using b.eval()
, we get:
现在,每当我们评估整个图时,例如使用b.eval()
,我们得到:
I tensorflow/core/kernels/logging_ops.cc:79] This is a: [1 3]
回答by Jeevan
Reiterating what others said, its not possible to check the values without running the graph.
重申其他人所说的话,不运行图表就无法检查值。
A simple snippet for anyone looking for an easy example to print values is as below. The code can be executed without any modification in ipython notebook
对于任何寻找简单示例来打印值的人来说,一个简单的片段如下。代码在ipython notebook中无需任何修改即可执行
import tensorflow as tf
#define a variable to hold normal random values
normal_rv = tf.Variable( tf.truncated_normal([2,3],stddev = 0.1))
#initialize the variable
init_op = tf.initialize_all_variables()
#run the graph
with tf.Session() as sess:
sess.run(init_op) #execute init_op
#print the random values that we sample
print (sess.run(normal_rv))
Output:
输出:
[[-0.16702934 0.07173464 -0.04512421]
[-0.02265321 0.06509651 -0.01419079]]
回答by Ben
Based on the answers above, with your particular code snippet you can print the product like this:
根据上面的答案,使用您的特定代码片段,您可以像这样打印产品:
import tensorflow as tf
#Initialize the session
sess = tf.InteractiveSession()
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
#print the product
print(product.eval())
#close the session to release resources
sess.close()
回答by Ganindu
Try this simple code! (it is self explanatory)
试试这个简单的代码!(这是不言自明的)
import tensorflow as tf
sess = tf.InteractiveSession() # see the answers above :)
x = [[1.,2.,1.],[1.,1.,1.]] # a 2D matrix as input to softmax
y = tf.nn.softmax(x) # this is the softmax function
# you can have anything you like here
u = y.eval()
print(u)
回答by smile
I think you need to get some fundamentals right. With the examples above you have created tensors (multi dimensional array). But for tensor flow to really work you have to initiate a "session" and run your "operation" in the session. Notice the word "session" and "operation". You need to know 4 things to work with tensorflow:
我认为你需要掌握一些基本知识。通过上面的示例,您已经创建了张量(多维数组)。但是要使张量流真正起作用,您必须启动一个“会话”并在会话中运行您的“操作”。注意“会话”和“操作”这两个词。您需要了解 4 件事才能使用 tensorflow:
- tensors
- Operations
- Sessions
- Graphs
- 张量
- 操作
- 会话
- 图表
Now from what you wrote out you have given the tensor, and the operation but you have no session running nor a graph. Tensor (edges of the graph) flow through graphs and are manipulated by operations (nodes of the graph). There is default graph but you can initiate yours in a session.
现在根据你写的内容,你已经给出了张量和操作,但你没有运行会话也没有图表。张量(图的边)流经图并由操作(图的节点)操纵。有默认图表,但您可以在会话中启动您的图表。
When you say print , you only access the shape of the variable or constant you defined.
当您说 print 时,您只能访问您定义的变量或常量的形状。
So you can see what you are missing :
所以你可以看到你缺少什么:
with tf.Session() as sess:
print(sess.run(product))
print (product.eval())
Hope it helps!
希望能帮助到你!
回答by npit
Please note that tf.Print()
will change the tensor name.
If the tensor you seek to print is a placeholder, feeding data to it will fail as the original name will not be found during feeding.
For example:
请注意,这tf.Print()
将更改张量名称。如果您要打印的张量是占位符,则向其提供数据将失败,因为在提供期间找不到原始名称。例如:
import tensorflow as tf
tens = tf.placeholder(tf.float32,[None,2],name="placeholder")
print(eval("tens"))
tens = tf.Print(tens,[tens, tf.shape(tens)],summarize=10,message="tens:")
print(eval("tens"))
res = tens + tens
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(res))
Output is:
输出是:
python test.py
Tensor("placeholder:0", shape=(?, 2), dtype=float32)
Tensor("Print:0", shape=(?, 2), dtype=float32)
Traceback (most recent call last):
[...]
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'placeholder' with dtype float
回答by Ahmed Gamal
You should think of TensorFlow Core programs as consisting of two discrete sections:
您应该将 TensorFlow Core 程序视为由两个独立的部分组成:
- Building the computational graph.
- Running the computational graph.
- 构建计算图。
- 运行计算图。
So for the code below you just Build the computational graph.
因此,对于下面的代码,您只需构建计算图。
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
You need also To initialize all the variables in a TensorFlow program , you must explicitly call a special operation as follows:
你还需要初始化一个 TensorFlow 程序中的所有变量,你必须显式调用一个特殊的操作,如下所示:
init = tf.global_variables_initializer()
Now you build the graph and initialized all variables ,next step is to evaluate the nodes, you must run the computational graph within a session. A session encapsulates the control and state of the TensorFlow runtime.
现在您构建图并初始化所有变量,下一步是评估节点,您必须在会话中运行计算图。一个会话封装了 TensorFlow 运行时的控制和状态。
The following code creates a Session object and then invokes its run method to run enough of the computational graph to evaluate product
:
下面的代码创建一个 Session 对象,然后调用它的 run 方法来运行足够的计算图来评估product
:
sess = tf.Session()
// run variables initializer
sess.run(init)
print(sess.run([product]))
回答by Giorgos Sfikas
You can check the output of a TensorObject without running the graph in a session, by enabling eager execution.
您可以检查TensorObject的输出,而不运行在会话中的图表中,使急于执行。
Simply add the following two lines of code:
import tensorflow.contrib.eager as tfe
tfe.enable_eager_execution()
只需添加以下两行代码:
import tensorflow.contrib.eager as tfe
tfe.enable_eager_execution()
right after you import tensorflow
.
就在你之后import tensorflow
。
The output of print product
in your example will now be:
tf.Tensor([[ 12.]], shape=(1, 1), dtype=float32)
print product
您的示例中的输出现在将是:
tf.Tensor([[ 12.]], shape=(1, 1), dtype=float32)
Note that as of now (November 2017) you'll have to install a Tensorflow nightly build to enable eager execution. Pre-built wheels can be found here.
请注意,截至目前(2017 年 11 月),您必须安装 Tensorflow nightly build 才能启用 Eager Execution。预制轮子可以在这里找到。