How can I change the tensorflow constant inside session for loop.
I am a learner and I am wondering how to update it in for loop
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))
Updated working code
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)
In TensorFlow, "constant" means exactly that: once you set it, you can't change it. To change the value that your TensorFlow program uses in the loop, you have two main choices: (1) using a tf.placeholder()
to feed in a value, or (2) using a tf.Variable
to store the value between steps, and tf.Variable.assign()
to update it.
Option 1 is much easier. Here's an example of how you could use it to implement your program using a placeholder:
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}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With