为了账号安全,请及时绑定邮箱和手机立即绑定

Tensorflow 多项式数组

Tensorflow 多项式数组

SMILET 2021-12-17 15:46:17
我正在尝试评估aX^2+bX+c,就像[a,b,c]\*[X*X X 1]在张量流中一样。我试过以下代码: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.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")  ...关于可能的替代方案有什么想法吗?
查看完整描述

2 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

你只需要稍微修改一下代码。的值不tf.Variable应该是tf.placeholder,否则运行时会导致你的初始化错误sess.run(tf.global_variables_initializer())。你可以用tf.stack它来代替。另外,请记住在运行时馈送数据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.]]


查看完整回答
反对 回复 2021-12-17
?
MM们

TA贡献1886条经验 获得超2个赞

我认为即使您仍然可以初始化一个依赖于这样的占位符的变量,W除非您添加更多代码来仅初始化未初始化的变量,否则将重复初始化。那是更多的努力。


希望我没有错过这种方法的其他低效率。


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.]]


查看完整回答
反对 回复 2021-12-17
  • 2 回答
  • 0 关注
  • 164 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号