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

标签 python tensorflow

目前,我有以下代码:

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/

相关文章:

tensorflow - 是否有可以同时在批量图像上运行的 Tensorflow 对象检测 API 的推理示例版本?

python - 使用字符串张量的 TensorFlow 字典查找

python - “模块”对象在服务器运行时不可调用,但在 django 控制台中可以调用

python - opencv 的段错误,在 Raspberry 上的 python 中

python - 字符串出现次数计数算法

python - 两个值匹配 pandas 时的累积计数

python - 使用 Python 在 OpenCV 中匹配模板

python - 如何在不同的 celery 任务 worker 中共享 tensorflow 模型

python-3.x - 找不到满足 tensorflow 要求的版本(来自版本 : ) No matching distribution found for tensorflow

python - 恢复和评估 Tensorflow 模型