如何在TensorFlow中打印Tensor对象的值?

Daw*_*y33 239 python tensorflow tensor

我一直在TensorFlow中使用矩阵乘法的介绍性示例.

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
Run Code Online (Sandbox Code Playgroud)

当我打印产品时,它将其显示为Tensor对象:

<tensorflow.python.framework.ops.Tensor object at 0x10470fcd0>
Run Code Online (Sandbox Code Playgroud)

但我怎么知道它的价值product

以下内容没有帮助:

print product
Tensor("MatMul:0", shape=TensorShape([Dimension(1), Dimension(1)]), dtype=float32)
Run Code Online (Sandbox Code Playgroud)

我知道图表会运行Sessions,但是没有任何方法可以在Tensor不运行图形的情况下检查对象的输出session

mrr*_*rry 229

评估对象实际值的最简单[A]方法Tensor是将其传递给Session.run()方法,或者Tensor.eval()在有默认会话时调用(即在with tf.Session():块中,或参见下文).通常[B],如果不在会话中运行某些代码,则无法打印张量的值.

如果您正在尝试编程模型,并且想要一种简单的方法来评估张量,那么tf.InteractiveSession您可以在程序开始时打开会话,然后将该会话用于所有Tensor.eval()(和Operation.run())调用.这在交互式设置中更容易,例如shell或IPython笔记本,当在Session任何地方传递对象时很繁琐.

这对于这么小的表达式来说可能看起来很愚蠢,但Tensorflow中的一个关键思想是延迟执行:构建大型复杂表达式非常便宜,当你想要评估它时,后端(你连接到它) a Session)能够更有效地安排其执行(例如并行执行独立部分并使用GPU).


[A]:要打印张量值而不将其返回到Python程序,可以使用tf.Print()运算符,正如Andrzej在另一个答案中建议的那样.请注意,您仍然需要运行图形的一部分来查看此op的输出,该输出将打印到标准输出.如果您正在运行分布式TensorFlow,tf.Print()则会将其输出打印到运行该操作的任务的标准输出.这意味着如果您使用https://colab.research.google.com或任何其他Jupyter Notebook,那么您将看不到tf.Print()笔记本中的输出; 在这种情况下,请参考这个答案,了解如何让它打印出来.

[B]:您可能可以使用实验tf.contrib.util.constant_value()函数来获取常量张量的值,但它并非用于一般用途,并且没有为许多运算符定义.

  • 可以在不调用Session.run()的情况下获得Tensor的一些属性.例如,您可以调用tensor.get_shape().在许多情况下,这提供了足够的信息来调试. (17认同)
  • 另请参阅下面的tf.Print操作系统的答案.我一直在谷歌搜索"tensorflow打印"时找到这个stackoverflow的答案,这个最佳答案让它听起来像没有tf.Print操作. (5认同)
  • `tf.Session()` 在 Tensorflow 2 中不起作用。您可以使用 `tf.compat.v1.Session()` 代替。 (4认同)
  • 我为答案添加了一些警告,因此现在应该更清楚了。(我不认为最初的提问者对获得张量的形状感兴趣,只是对值感兴趣。) (2认同)

And*_*bis 151

虽然其他答案是正确的,在评估图表之前无法打印该值,但在评估图表之后,他们并没有谈到在图表中实际打印值的一种简单方法.

在评估图形时(使用runeval)查看张量值的最简单方法是使用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)
Run Code Online (Sandbox Code Playgroud)

现在,每当我们评估整个图表时,例如使用b.eval(),我们得到:

I tensorflow/core/kernels/logging_ops.cc:79] This is a: [1 3]
Run Code Online (Sandbox Code Playgroud)

  • 将a = tf.print中的a用于其他内容非常重要!tf.print(a,[a])否则不会做任何事情 (34认同)
  • 请注意,`tf.Print()`已被弃用且(现在)已被删除.而是使用`tf.print()`.请参阅文档:https://www.tensorflow.org/api_docs/python/tf/Print和https://www.tensorflow.org/api_docs/python/tf/print. (7认同)
  • 我们可以使用`a.eval()`然后! (5认同)
  • @FabioDias 我不认为我明白你的意思?有空的时候可以详细说一下吗... (3认同)

Jee*_*van 27

重申别人说的话,不运行图表就无法检查数值.

任何寻找打印值的简单示例的人都可以使用一个简单的代码段如下.代码可以在ipython笔记本中执行而无需任何修改

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))
Run Code Online (Sandbox Code Playgroud)

输出:

[[-0.16702934  0.07173464 -0.04512421]
 [-0.02265321  0.06509651 -0.01419079]]
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考:'警告:tensorflow:来自<ipython-input-25-8583e1c5b3d6>:1:initialize_all_variables(来自tensorflow.python.ops.variables)已弃用,将于2017-03-02之后删除.更新说明:改为使用'tf.global_variables_initializer' (2认同)

Sal*_*ali 20

不,如果不运行图形(做session.run()),就无法看到张量的内容.你能看到的唯一的东西是:

  • 张量的维数(但我认为对于TF所具有的操作列表来计算它并不困难)
  • 将用于生成张量的操作的类型(transpose_1:0,random_uniform:0)
  • 张量中的元素类型(float32)

我没有在文档中找到这个,但我相信变量的值(以及一些常量在分配时不计算).


看看这个例子:

import tensorflow as tf
from datetime import datetime
dim = 7000
Run Code Online (Sandbox Code Playgroud)

第一个例子,我只是启动一个恒定的随机数张量运行大致相同的时间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
Run Code Online (Sandbox Code Playgroud)

在第二种情况下,实际评估常量并分配值,时间明显取决于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
Run Code Online (Sandbox Code Playgroud)

你可以通过计算一些事情来更清楚地说明(d = tf.matrix_determinant(m1)记住时间会运行O(dim^2.8))

PS我发现它是在文档中解释的:

Tensor对象是操作结果的符号句柄,但实际上并不保存操作输出的值.


smi*_*ile 14

我认为你需要得到一些正确的基础知识.通过上面的示例,您已经创建了张量(多维数组).但是要使张量流真正起作用,你必须启动一个" 会话 "并在会话中运行你的" 操作 ".注意"会话"和"操作"这个词.你需要知道使用te​​nsorflow的4件事:

  1. 张量
  2. 操作
  3. 会议
  4. 图表

现在从你所写的内容中你已经给出了张量和操作,但你没有运行会话也没有图表.张量(图的边缘)流过图形并由操作(图形的节点)操纵.有默认图表,但您可以在会话中启动您的图表.

当您说打印时,您只能访问您定义的变量或常量的形状.

所以你可以看到你缺少的东西:

 with tf.Session() as sess:     
           print(sess.run(product))
           print (product.eval())
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!


Vis*_*ati 10

在最近的Tensorflow 1.13.1中

import tensorflow as tf
tf.enable_eager_execution()
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

#print the product
print(product)         # tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(product.numpy()) # [[12.]]
Run Code Online (Sandbox Code Playgroud)

在Tensorflow 2.0中,默认情况下启用了eager模式。因此以下代码适用于TF2.0。

import tensorflow as tf
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

#print the product
print(product)         # tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(product.numpy()) # [[12.]]
Run Code Online (Sandbox Code Playgroud)


Ben*_*Ben 8

根据上面的答案,使用您的特定代码段,您可以打印产品,如下所示:

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()
Run Code Online (Sandbox Code Playgroud)


Mad*_*yar 8

在 Tensorflow 2.0+(或 Eager 模式环境)中,您可以调用.numpy()方法:

import tensorflow as tf

matrix1 = tf.constant([[3., 3.0]])
matrix2 = tf.constant([[2.0],[2.0]])
product = tf.matmul(matrix1, matrix2)

print(product.numpy()) 
Run Code Online (Sandbox Code Playgroud)


小智 8

我不确定我是否在这里遗漏了,但我认为最简单、最好的方法是使用tf.keras.backend.get_valueAPI。

print(product)
>>tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(tf.keras.backend.get_value(product))
>>[[12.]]
Run Code Online (Sandbox Code Playgroud)


Gio*_*kas 7

您可以通过启用急切执行来检查TensorObject的输出,而无需在会话中运行图形.

只需添加以下两行代码: import tensorflow.contrib.eager as tfe tfe.enable_eager_execution()

之后你的权利import tensorflow.

print product您的示例中的输出现在将是: tf.Tensor([[ 12.]], shape=(1, 1), dtype=float32)

请注意,截至目前(2017年11月),您必须安装Tensorflow每晚构建以启用急切执行.这里可以找到预制轮子.


cs9*_*s95 6

tf.keras.backend.eval 对于评估小表达式很有用。

tf.keras.backend.eval(op)
Run Code Online (Sandbox Code Playgroud)

TF 1.x和TF 2.0兼容。


最小的可验证示例

from tensorflow.keras.backend import eval

m1 = tf.constant([[3., 3.]])
m2 = tf.constant([[2.],[2.]])

eval(tf.matmul(m1, m2))
# array([[12.]], dtype=float32)
Run Code Online (Sandbox Code Playgroud)

这很有用,因为您不必显式创建Sessionor InteractiveSession


npi*_*pit 5

请注意,这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))
Run Code Online (Sandbox Code Playgroud)

输出为:

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
Run Code Online (Sandbox Code Playgroud)


Ahm*_*mal 5

您应该将TensorFlow Core程序视为由两个独立的部分组成:

  • 构建计算图.
  • 运行计算图.

因此,对于下面的代码,您只需构建计算图.

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
Run Code Online (Sandbox Code Playgroud)

您还需要要初始化TensorFlow程序中的所有变量,您必须显式调用特殊操作,如下所示:

init = tf.global_variables_initializer()
Run Code Online (Sandbox Code Playgroud)

现在您构建图并初始化所有变量,下一步是评估节点,您必须在会话中运行计算图.会话封装TensorFlow运行时的控件和状态.

以下代码创建一个Session对象,然后调用其run方法运行足够的计算图来评估product:

sess = tf.Session()
// run variables initializer
sess.run(init)

print(sess.run([product]))
Run Code Online (Sandbox Code Playgroud)


cha*_*esh 5

您可以使用 Keras,单行答案将使用如下eval方法:

import keras.backend as K
print(K.eval(your_tensor))
Run Code Online (Sandbox Code Playgroud)