300

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

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

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

<tensorflow.python.framework.ops.Tensor object at 0x10470fcd0>

但我怎么知道 的价值product

以下没有帮助:

print product
Tensor("MatMul:0", shape=TensorShape([Dimension(1), Dimension(1)]), dtype=float32)

我知道图形在 上运行Sessions,但有没有什么办法可以检查Tensor对象的输出而不在 a 中运行图形session

4

24 回答 24

271

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

如果您正在尝试编程模型,并且想要一种简单的方法来评估张量,那么tf.InteractiveSession您可以在程序开始时打开一个会话,然后将该会话用于所有Tensor.eval()(and Operation.run()) 调用。这在交互式环境中会更容易,例如 shell 或 IPython 笔记本,因为Session到处传递一个对象很乏味。例如,以下在 Jupyter 笔记本中有效:

with tf.Session() as sess:  print(product.eval()) 

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


[A]:要打印张量的值而不将其返回到您的 Python 程序,您可以使用tf.print()运算符,正如Andrzej 在另一个答案中所建议的那样。根据官方文档:

为了确保操作符运行,用户需要将生成的操作传递给tf.compat.v1.Session的 run 方法,或者通过使用 ) 指定将操作作为执行操作的控制依赖项,tf.compat.v1.control_dependencies([print_op]打印到标准输出。

另请注意:

在 Jupyter 笔记本和 colabs 中,tf.print打印到笔记本单元输出。它不会写入笔记本内核的控制台日志。

[B]:如果给定张量的值是可有效计算的,您也许可以使用该tf.get_static_value()函数来获取给定张量的常量值。

于 2015-11-10T15:41:24.600 回答
163

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

每当评估图形时(使用runor 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)

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

I tensorflow/core/kernels/logging_ops.cc:79] This is a: [1 3]
于 2016-03-29T23:13:22.653 回答
28

重申其他人所说的,如果不运行图表就无法检查值。

对于任何寻找打印值的简单示例的人来说,一个简单的片段如下所示。在 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))

输出:

[[-0.16702934  0.07173464 -0.04512421]
 [-0.02265321  0.06509651 -0.01419079]]
于 2016-05-31T10:28:56.297 回答
20

不,如果不运行图表(执行session.run()),您将看不到张量的内容。你能看到的只有:

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

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


看看这个例子:

import tensorflow as tf
from datetime import datetime
dim = 7000

第一个例子,我只是启动一个随机数的常量张量,几乎在同一时间运行,与 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

在第二种情况下,实际评估常量并分配值,时间显然取决于 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

您可以通过计算一些东西来使其更清楚(请d = tf.matrix_determinant(m1)记住,时间会流逝O(dim^2.8)

PS我发现它在文档中进行了解释:

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

于 2015-11-10T22:20:06.370 回答
19

Tensorflow 1.x

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.]]

在 Tensorflow 2.x 中,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.]]
于 2019-04-17T22:35:10.353 回答
15

我认为您需要正确掌握一些基础知识。通过上面的示例,您已经创建了张量(多维数组)。但是要让张量流真正起作用,您必须启动一个“会话”并在会话中运行您的“操作”。注意单词“会话”和“操作”。使用 tensorflow 需要了解 4 件事:

  1. 张量
  2. 运营
  3. 会话
  4. 图表

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

当您说 print 时,您只能访问您定义的变量或常量的形状。

所以你可以看到你缺少什么:

 with tf.Session() as sess:     
           print(sess.run(product))
           print (product.eval())

希望能帮助到你!

于 2017-02-22T00:54:45.957 回答
13

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

tf.keras.backend.eval(op)

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)

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

于 2019-06-27T18:13:57.573 回答
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()) 
于 2019-04-17T21:00:03.087 回答
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()
于 2017-01-11T00:18:38.700 回答
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 每晚构建版本才能启用 Eager Execution。预制轮子可以在这里找到。

于 2017-11-01T15:49:25.150 回答
5

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

import keras.backend as K
print(K.eval(your_tensor))
于 2019-07-27T15:04:31.997 回答
5

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

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

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

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

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

init = tf.global_variables_initializer()

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

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

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

print(sess.run([product]))
于 2017-07-01T11:49:59.460 回答
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))

输出是:

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
于 2017-06-24T22:12:28.033 回答
4

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

print(product)
>>tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(tf.keras.backend.get_value(product))
>>[[12.]]
于 2020-11-29T11:00:45.617 回答
3

试试这个简单的代码!(这是不言自明的)

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)
于 2017-02-12T14:11:34.543 回答
3

在 Tensorflow V2 中,使用以下方式打印张量值:tf.keras.backend.print_tensor(x, message='')

于 2020-11-29T09:16:30.537 回答
2

即使在阅读了所有答案之后,我也很难理解需要什么,直到我执行此操作。TensofFlow 对我来说也是新的。

def printtest():
x = tf.constant([1.0, 3.0])
x = tf.Print(x,[x],message="Test")
init = (tf.global_variables_initializer(), tf.local_variables_initializer())
b = tf.add(x, x)
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(b))
    sess.close()

但是您仍然可能需要执行会话返回的值。

def printtest():
    x = tf.constant([100.0])
    x = tf.Print(x,[x],message="Test")
    init = (tf.global_variables_initializer(), tf.local_variables_initializer())
    b = tf.add(x, x)
    with tf.Session() as sess:
        sess.run(init)
        c = sess.run(b)
        print(c)
        sess.close()
于 2018-04-18T13:25:24.623 回答
2

您可以在会话中打印出张量值,如下所示:

import tensorflow as tf

a = tf.constant([1, 1.5, 2.5], dtype=tf.float32)
b = tf.constant([1, -2, 3], dtype=tf.float32)
c = a * b

with tf.Session() as sess:
    result = c.eval()
   
print(result)
于 2021-02-13T00:40:41.407 回答
1

使用https://www.tensorflow.org/api_docs/python/tf/print中提供的提示,我使用该log_d函数打印格式化字符串。

import tensorflow as tf

def log_d(fmt, *args):
    op = tf.py_func(func=lambda fmt_, *args_: print(fmt%(*args_,)),
                    inp=[fmt]+[*args], Tout=[])
    return tf.control_dependencies([op])


# actual code starts now...

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

with log_d('MAT1: %s, MAT2: %s', matrix1, matrix2): # this will print the log line
    product = tf.matmul(matrix1, matrix2)

with tf.Session() as sess:
    sess.run(product)
于 2019-08-09T16:12:23.053 回答
1

启用 tensorflow 1.10 之后引入的急切执行。它非常易于使用。

# Initialize session
import tensorflow as tf
tf.enable_eager_execution()


# Some tensor we want to print the value of
a = tf.constant([1.0, 3.0])

print(a)
于 2019-05-09T19:33:08.427 回答
1

基本上,在 tensorflow 中,当您创建任何类型的张量时,它们会被创建并存储在其中,只有在运行 tensorflow 会话时才能访问。假设您已经创建了一个常量张量
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
,而无需运行会话,您可以获得
- op: 一个操作。计算此张量的操作。
- value_index:一个整数。产生此张量的操作端点的索引。
- dtype:一个 DType。存储在此张量中的元素类型。

要获取值,您可以使用所需的张量运行会话:

with tf.Session() as sess:
    print(sess.run(c))
    sess.close()

输出将是这样的:

数组([[1., 2., 3.], [4., 5., 6.]], dtype=float32)

于 2018-08-01T09:09:48.923 回答
0
import tensorflow as tf
sess = tf.InteractiveSession()
x = [[1.,2.,1.],[1.,1.,1.]]    
y = tf.nn.softmax(x)           

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

print(product.eval())
tf.reset_default_graph()
sess.close()
于 2018-04-05T04:41:37.773 回答
0

tf.Print 现在已被弃用,这里是如何使用 tf.print(小写 p)来代替。

虽然运行会话是一个不错的选择,但它并不总是可行的方法。例如,您可能希望在特定会话中打印一些张量。

新的 print 方法返回一个没有输出张量的打印操作:

print_op = tf.print(tensor_to_print)

由于它没有输出,因此您不能像使用 tf.Print 那样将其插入图表中。相反,您可以将其添加到会话中的控制依赖项以使其打印。

sess = tf.compat.v1.Session()
with sess.as_default():
  tensor_to_print = tf.range(10)
  print_op = tf.print(tensor_to_print)
with tf.control_dependencies([print_op]):
  tripled_tensor = tensor_to_print * 3
sess.run(tripled_tensor)

有时,在较大的图中,可能部分在子函数中创建,将 print_op 传播到会话调用很麻烦。然后,tf.tuple 可用于将打印操作与另一个操作耦合,然后无论哪个会话执行代码,该操作都将与该操作一起运行。这是如何完成的:

print_op = tf.print(tensor_to_print)
some_tensor_list = tf.tuple([some_tensor], control_inputs=[print_op])
# Use some_tensor_list[0] instead of any_tensor below.
于 2019-11-14T14:47:09.163 回答
-2

问题:如何在 TensorFlow 中打印张量对象的值?

回答:

import tensorflow as tf

# Variable
x = tf.Variable([[1,2,3]])

# initialize
init = (tf.global_variables_initializer(), tf.local_variables_initializer())

# Create a session
sess = tf.Session()

# run the session
sess.run(init)

# print the value
sess.run(x)
于 2019-04-17T18:34:20.653 回答