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

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

当我打印乘积时,它显示为一个张量对象:

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

但是我怎么知道产品的价值呢?

下面的方法不起作用:

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

我知道图在会话上运行,但是没有任何方法可以检查张量对象的输出而不在会话中运行图吗?


当前回答

你可以打印出session中的张量值,如下所示:

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)

其他回答

你可以打印出session中的张量值,如下所示:

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)

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

通过启用即时执行,你可以检查TensorObject的输出,而不用在会话中运行图。

只需添加以下两行代码: 导入tensorflow.contrib.eager为tfe tfe.enable_eager_execution ()

在你导入tensorflow之后。

在你的例子中打印产品的输出现在将是: 特遣部队。张量([[12。[],形状=(1,1),dtype=float32)

请注意,从现在(2017年11月)开始,你必须每晚安装一个Tensorflow构建来实现快速执行。预建车轮可以在这里找到。

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)

这很有用,因为您不必显式地创建Session或InteractiveSession。

基本上,在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([[1st, 2nd, 3rd], [4th, 5th, 6th]], dtype=float32)