为什么我不能分配给这个占位符?

2024-05-23 17:35:20 发布

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

以下是我使用的部分代码:

subX = tf.placeholder(tf.float32, ())
op1 = tf.assign(subX,x_hat-x)

当我执行这个代码片段时,我得到:

AttributeError: 'Tensor' object has no attribute 'assign'

但是,每当我执行此操作时,它都可以正常工作:

subX = tf.Variable(tf.zeros((299, 299, 3)))
op1 = tf.assign(subX,x_hat-x)

我不明白为什么后者有效,而前者不行。这个答案基本上是说变量需要一个初始值,而占位符不需要。在这两种情况下,我只是在覆盖它们,那又有什么关系呢? What's the difference between tf.placeholder and tf.Variable?


Tags: no代码objecttfhatattributevariableplaceholder
1条回答
网友
1楼 · 发布于 2024-05-23 17:35:20

占位符不能这样使用。相反,它是计算图的输入点。你可以这样做:

my_var = tf.placeholder(tf.float32)
my_const = tf.constant(12.3)

with tf.Session() as sess:
    result = sess.run(my_const*my_var, feed_dict={my_var: 45.7})

然后,print(result)将给出float562.11005。你知道吗

我的意思是占位符(my_var,这里)只是一个符号节点,表示计算图形的输入,在图形创建时尝试为这种表示赋值在概念上是错误的。 如果你想深入研究张量流的计算模型,你可能会对this TF graph explanation感兴趣。你知道吗

相关问题 更多 >