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

我一直在使用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不运行图形的情况下检查对象的输出session吗?

I have been using the introductory example of matrix multiplication in 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:

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

But how do I know the value of 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?


回答 0

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

如果您正在试验编程模型,并且想要一种简单的方法来评估张量,则可以在程序开始时打开一个会话,然后将该会话用于所有Tensor.eval()(和Operation.run())调用。当在一个Session无处不在的对象周围传递乏味的代码时,在诸如外壳或IPython笔记本之类的交互式设置中,这可能会更容易。例如,以下内容在Jupyter笔记本中起作用:

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

对于这么小的表达式来说,这似乎很愚蠢,但是Tensorflow 1.x的关键思想之一是推迟执行:构建一个大型而复杂的表达式非常便宜,并且当您要对其进行评估时,后端与您连接的Session)能够更有效地安排其执行时间(例如,并行执行独立的部分并使用GPU)。


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

为了确保操作员能够运行,用户需要将产生的op传递给tf.compat.v1.Session的run方法,或者通过将其指定为来将op用作已执行op的控件依赖项tf.compat.v1.control_dependencies([print_op],并打印到标准输出中。

另请注意:

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

[B]:如果可以有效tf.get_static_value()地计算给定张量的值,则可以使用该函数获取其恒定值。

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.

If you are experimenting with the programming model, and want an easy way to evaluate tensors, the 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:

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


[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:

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 with tf.compat.v1.control_dependencies([print_op]), which is printed to standard output.

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.

[B]: You might be able to use the tf.get_static_value() function to get the constant value of the given tensor if its value is efficiently calculable.


回答 1

尽管其他答案是正确的,即您不能在评估图形之前就无法打印该值,但它们并没有讨论在评估图形后在图形内部实际打印值的一种简单方法。

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

现在,无论何时我们评估整个图形,例如使用b.eval(),我们都会得到:

I tensorflow/core/kernels/logging_ops.cc:79] This is a: [1 3]

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:

# 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:

I tensorflow/core/kernels/logging_ops.cc:79] This is a: [1 3]

回答 2

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

想要寻找简单示例来打印值的任何人的简单摘录如下。该代码无需修改即可在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]]

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

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

回答 3

不,如果不运行图形,就无法看到张量的内容(这样做session.run())。您只能看到的是:

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

我没有在文档中找到此信息,但我相信变量的值(以及某些常量在赋值时并未计算)。


看一下这个例子:

import tensorflow as tf
from datetime import datetime
dim = 7000

第一个示例中,我只是初始化一个随机数的常数Tensor,而在不显着的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对象是操作结果的符号句柄,但实际上并不保存操作输出的值。

No, you can not see the content of the tensor without running the graph (doing session.run()). The only things you can see are:

  • the dimensionality of the tensor (but I assume it is not hard to calculate it for the list of the operations that 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)

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)

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)

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))

P.S. I found were it is explained in documentation:

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.


回答 4

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

  1. 张量
  2. 运作方式
  3. 届会
  4. 图表

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

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

这样您就可以看到丢失的内容:

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

希望能帮助到你!

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:

  1. tensors
  2. Operations
  3. Sessions
  4. 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.

So you can see what you are missing :

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

Hope it helps!


回答 5

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

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

With Tensorflow 2.x, eager mode is enabled by default. so the following code works with 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.]]

回答 6

根据上述答案,使用您的特定代码段,您可以像这样打印产品:

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()

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()

回答 7

在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()) 

In Tensorflow 2.0+ (or in Eager mode environment) you can call .numpy() method:

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()) 

回答 8

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

tf.keras.backend.eval is useful for evaluating small expressions.

tf.keras.backend.eval(op)

TF 1.x and TF 2.0 compatible.


Minimal Verifiable Example

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)

This is useful because you do not have to explicitly create a Session or InteractiveSession.


回答 9

您可以通过启用急切执行来检查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构建以启用渴望执行的功能。预制的车轮可以在这里找到。

You can check the output of a TensorObject without running the graph in a session, by enabling eager execution.

Simply add the following two lines of code: import tensorflow.contrib.eager as tfe tfe.enable_eager_execution()

right after you import tensorflow.

The output of print product in your example will now be: 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.


回答 10

请注意,这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

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:

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

回答 11

您应该将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]))

You should think of TensorFlow Core programs as consisting of two discrete sections:

  • 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:

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.

The following code creates a Session object and then invokes its run method to run enough of the computational graph to evaluate product :

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

print(sess.run([product]))

回答 12

您可以使用Keras,单行答案将是使用这样的eval方法:

import keras.backend as K
print(K.eval(your_tensor))

You can use Keras, one-line answer will be to use eval method like so:

import keras.backend as K
print(K.eval(your_tensor))

回答 13

试试这个简单的代码!(不言而喻)

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)

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)

回答 14

即使阅读完所有答案,我仍然不容易理解需要执行的操作,直到执行完为止。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()

I didn’t find it easy to understand what is required even after reading all the answers until I executed this. TensofFlow is new to me too.

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()

But still you may need the value returned by executing the session.

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()

回答 15

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

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

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

输出将是这样的:

array([[1。,2.,3.],[4.,5.,6.]],dtype = float32)

Basically, in tensorflow when you create a tensor of any sort they are created and stored inside which can be accessed only when you run a tensorflow session. Say you have created a constant tensor
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Without running a session, you can get
op: An Operation. Operation that computes this tensor.
value_index: An int. Index of the operation’s endpoint that produces this tensor.
dtype: A DType. Type of elements stored in this tensor.

To get the values you can run a session with the tensor you require as:

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

The output will be something like this:

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


回答 16

启用1.10版后在tensorflow中引入的热切执行。它很容易使用。

# 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)

Enable the eager execution which is introduced in tensorflow after version 1.10. It’s very easy to use.

# 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)

回答 17

使用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)

Using tips provided in https://www.tensorflow.org/api_docs/python/tf/print I use the log_d function to print formatted strings.

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)

回答 18

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()
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()

回答 19

现在不建议使用tf.Print,这是使用tf.print(小写p)的方法。

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

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

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.

tf.Print is now deprecated, here’s how to use tf.print (lowercase p) instead.

While running a session is a good option, it is not always the way to go. For instance, you may want to print some tensor in a particular session.

The new print method returns a print operation which has no output tensors:

print_op = tf.print(tensor_to_print)

Since it has no outputs, you can’t insert it in a graph the same way as you could with tf.Print. Instead, you can you can add it to control dependencies in your session in order to make it 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)

Sometimes, in a larger graph, maybe created partly in subfunctions, it is cumbersome to propagate the print_op to the session call. Then, tf.tuple can be used to couple the print operation with another operation, which will then run with that operation whichever session executes the code. Here’s how that is done:

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.

回答 20

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

回答:

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)

Question: How to print the value of a Tensor object in TensorFlow?

Answer:

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)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。