Tensorflow 多项式数组

我正在尝试评估aX^2+bX+c,就像[a,b,c]\*[X*X X 1]在张量流中一样。


我试过以下代码:


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.Variable([X*X,X,1.0], dtype=tf.float32, name="Filter")

F=tf.reshape(F,[3,1])

print(W.shape)

print(F.shape)

Y=tf.matmul(W,F)

with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())

    for i in range(10): 

        sess.run(Y, feed_dict={X: i})

    Y=sess.run(Y)

print("Y:",Y)

但是,初始化程序并不高兴:


(1, 3)

(3, 1)

...

tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'X' with dtype float

     [[{{node X}}]]

During handling of the above exception, another exception occurred:

...

Caused by op 'X', defined at:

  File "sample.py", line 2, in <module>

    X = tf.placeholder(tf.float32, name="X")  

...

关于可能的替代方案有什么想法吗?


SMILET
浏览 165回答 2
2回答

哔哔one

你只需要稍微修改一下代码。的值不tf.Variable应该是tf.placeholder,否则运行时会导致你的初始化错误sess.run(tf.global_variables_initializer())。你可以用tf.stack它来代替。另外,请记住在运行时馈送数据sess.run(Y)。import tensorflow as tfX = 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:&nbsp; &nbsp; sess.run(tf.global_variables_initializer())&nbsp; &nbsp; for i in range(10):&nbsp; &nbsp; &nbsp; &nbsp; Y_val = sess.run(Y, feed_dict={X: i})&nbsp; &nbsp; &nbsp; &nbsp; print("Y:",Y_val)Y: [[1.]]Y: [[4.]]Y: [[9.]]Y: [[16.]]Y: [[25.]]Y: [[36.]]Y: [[49.]]Y: [[64.]]Y: [[81.]]Y: [[100.]]

MM们

我认为即使您仍然可以初始化一个依赖于这样的占位符的变量,W除非您添加更多代码来仅初始化未初始化的变量,否则将重复初始化。那是更多的努力。希望我没有错过这种方法的其他低效率。import tensorflow as tfsess = 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):&nbsp; &nbsp; sess.run([init], feed_dict={X: i})&nbsp; &nbsp; print(sess.run(Y))[[1.]][[4.]][[9.]][[16.]][[25.]][[36.]][[49.]][[64.]][[81.]][[100.]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python