如何更改会话 for loop 内的张量流常量。
我是学习者,我想知道如何在for循环中更新它
import tensorflow as tf
import numpy as np
looperCount = 10
data = np.random.randint(2, size=looperCount)
x = tf.constant(data, name='x')
y = tf.Variable((5 * (x * x)) - (3 * x) + 15, name="y")
model = tf.initialize_all_variables()
with tf.Session() as sess:
for i in range(looperCount):
sess.run(model)
data = np.random.randint(2, size=looperCount)
x = tf.constant(data, name='x')
avg = np.average(sess.run(y))
print "avg - {}, sess - {}".format(avg, sess.run(y))
更新了工作代码
import tensorflow as tf
import numpy as np
looperCount = 10
x = tf.placeholder("float", looperCount)
y = (5 * (x * x)) - (3 * x) + 15
with tf.Session() as sess:
for i in range(looperCount):
data = np.random.randint(10, size=looperCount)
result_y = sess.run(y, feed_dict={x: data})
avg = np.average(result_y)
print "avg - {:10} valy - {:10}".format("{:.2f}".format(avg), result_y)
答案 0 :(得分:9)
在TensorFlow中,"常数"意思是:一旦你设置它,你就无法改变它。要更改TensorFlow程序在循环中使用的值,您有两个主要选择:(1)使用tf.placeholder()
输入值,或(2)使用tf.Variable
存储值在步骤之间,并tf.Variable.assign()
更新它。
选项1更容易。以下是如何使用占位符来实现程序的示例:
import tensorflow as tf
import numpy as np
looperCount = 10
data = np.random.randint(2, size=looperCount)
x = tf.placeholder(tf.float64, shape=[2], name="x")
y = tf.Variable((5 * (x * x)) - (3 * x) + 15, name="y")
init_op = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init_op)
for i in range(looperCount):
data = np.random.randint(2, size=looperCount)
avg = np.average(sess.run(y, feed_dict={x: data}))
print "avg - {}, sess - {}".format(avg, sess.run(y, feed_dict={x: data}))