gpt4 book ai didi

python - 如何使用占位符分配 tf.Variables?

转载 作者:太空宇宙 更新时间:2023-11-03 23:57:19 24 4
gpt4 key购买 nike

目前,我有以下代码:

x = tf.placeholder(tf.int32, name = "x")
y = tf.Variable(0, name="y")
y = 2*x**2 + 5
for i in range(1,10):
print("Value of y for x = ",i, " is: ",sess.run(y, feed_dict={x:i}))

但是,当我尝试在 tensorboard 上显示它时,它变得一团糟。理想情况下我想做 y= tf.Variable(2*x**2 +5) 但 tensorflow 抛出一个错误告诉我 x 未初始化。或者也许我不应该使用 tf.Variable 而使用其他东西?

最佳答案

如果你真的想用 tf.Variable 做到这一点,您可以通过两种方式做到这一点。您可以使用所需的表达式作为变量的初始化值。然后,当您初始化变量时,您在 feed_dict 中传递 x 值。

import tensorflow as tf

# Placeholder shape must be specified or use validate_shape=False in tf.Variable
x = tf.placeholder(tf.int32, (), name="x")
# Initialization value for variable is desired expression
y = tf.Variable(2 * x ** 2 + 5, name="y")
with tf.Session() as sess:
for i in range(1,10):
# Initialize variable on each iteration
sess.run(y.initializer, feed_dict={x: i})
# Show value
print("Value of y for x =", i , "is:", sess.run(y))

或者,您可以用 tf.assign 做同样的事情手术。在这种情况下,您在运行分配时传递了 x 值。

import tensorflow as tf

# Here placeholder shape is not stricly required as tf.Variable already gives the shape
x = tf.placeholder(tf.int32, name="x")
# Specify some initialization value for variable
y = tf.Variable(0, name="y")
# Assign expression value to variable
y_assigned = tf.assign(y, 2 * x** 2 + 5)
# Initialization can be skipped in this case since we always assign new value
with tf.Graph().as_default(), tf.Session() as sess:
for i in range(1,10):
# Assign vale to variable in each iteration (and get value after assignment)
print("Value of y for x =", i , "is:", sess.run(y_assigned, feed_dict={x: i}))

然而,作为pointed out by Nakor ,如果 y 只是被认为是 x 所取值的表达式的结果,则可能不需要变量。变量的用途是保存一个值,该值将在以后调用 run 时保留。因此,只有当您想根据 xy 设置为某个值时才需要它,然后即使 x 更改也保持相同的值(或者即使根本没有提供 x)。

关于python - 如何使用占位符分配 tf.Variables?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57090420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com