Tensorflow Polynomial Array
I'm trying to evaluate aX^2+bX+c, as [a,b,c]\*[X*X X 1] in tensorflow. I've tried the following code: import tensorflow as tf X = tf.placeholder(tf.float32, name='X') W = tf.Variab
Solution 1:
You just need to modify the code a little bit. The value of tf.Variable
should not be tf.placeholder
, otherwise it will cause your initialization error when running sess.run(tf.global_variables_initializer())
. You can use tf.stack
instead of it.
In addition, please remember to feed data when you run sess.run(Y)
.
import tensorflow as tf
X = tf.placeholder(tf.float32, name="X")
W = tf.Variable([1,2,1], dtype=tf.float32, name="weights")
W = tf.reshape(W,[1,3])
F = tf.stack([X*X,X,1.0])
F = tf.reshape(F,[3,1])
Y = tf.matmul(W,F)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(10):
Y_val = sess.run(Y, feed_dict={X: i})
print("Y:",Y_val)
Y: [[1.]]
Y: [[4.]]
Y: [[9.]]
Y: [[16.]]
Y: [[25.]]
Y: [[36.]]
Y: [[49.]]
Y: [[64.]]
Y: [[81.]]
Y: [[100.]]
Solution 2:
I think even though you could still initialize a variable that depends on a placeholder like this, W
will get initialized repeatedly unless you add more code to initialize only uninitialized variables. That is more effort.
Hope I haven't missed other inefficiencies in this approach.
import tensorflow as tf
sess = tf.InteractiveSession()
X = tf.placeholder(tf.float32, name="X")
W = tf.Variable([1, 2, 1], dtype=tf.float32, name="weights")
W = tf.reshape(W, [1, 3])
var = tf.reshape([X*X,X,1],[3,1])
F = tf.get_variable('F', dtype=tf.float32, initializer=var)
init = tf.global_variables_initializer()
Y=tf.matmul(W,F)
for i in range(10):
sess.run([init], feed_dict={X: i})
print(sess.run(Y))
[[1.]][[4.]][[9.]][[16.]][[25.]][[36.]][[49.]][[64.]][[81.]][[100.]]
Post a Comment for "Tensorflow Polynomial Array"