Tensorflow在打印时输出错误

时间:2018-01-30 10:15:18

标签: python python-3.x tensorflow

我已经开始学习张量流, 试图执行代码并不断得到错误的结果

import tensorflow as tf

# Immutable constants
a = tf.constant(6,name='constant_a')
b = tf.constant(3,name='contant_b')
c = tf.constant(10,name='contant_c')
d = tf.constant(5,name='contant_d')

mul = tf.multiply(a,b,name='mul')
div = tf.div(c,d,name="div")
# Output of the multiplication what needs to be added
addn = tf.add_n([mul,div],name="addn")
# Print out the result
print (addn)

结果只是

 Tensor("addn:0", shape=(), dtype=int32) 

奇怪的输出在执行所有计算后需要addn的值

1 个答案:

答案 0 :(得分:2)

问题是

print (addn)

打印数据只是给出了

的名称
 Tensor("addn:0", shape=(), dtype=int32) 

张量,形状及其数据类型

在任何时间点都没有给出价值。 这是因为上面的代码没有运行/执行。 它刚刚构造了张量流中的图形但未执行以获得结果要执行它session是必需的

你可以添加几行,创建会话然后打印

sess = tf.Session()
print(sess.run(addn))

<强>输出    你会得到输出20

  

a * b + c / d = 6 * 3 + 10/5 = 18 + 2 = 20

完整代码

d = tf.constant(5,name='contant_d')

mul = tf.multiply(a,b,name='mul')
div = tf.div(c,d,name="div")

# Output of the multiplication what needs to be added
addn = tf.add_n([mul,div],name="addn")
print (addn)

"""
Printing data just gives the name of the Tensor ,shape and its data type
doesn't give  value it hold anypoint of time
This is because above code is not run
It has just constructed the Graph in tensorflow but haven't executed to get the result
To Execute it session is required  
"""
sess = tf.Session()
print(sess.run(addn))