普林张量流错误输出

2024-05-20 03:42:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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的值


Tags: the代码nameimportdivtftensorflowas
1条回答
网友
1楼 · 发布于 2024-05-20 03:42:32

问题是

print (addn)

打印数据只是给出

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

张量、形状及其数据类型

不给它任何时间点的价值。 这是因为上面的代码没有运行/执行。 它刚刚在tensorflow中构建了图形,但尚未执行以获得执行它的结果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))

相关问题 更多 >