gpt4 book ai didi

python - tensorflow 多项式数组

转载 作者:行者123 更新时间:2023-12-01 01:05:46 24 4
gpt4 key购买 nike

我正在尝试评估aX^2+bX+c,如 tensorflow 中的[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")
...

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

最佳答案

只需稍微修改一下代码即可。 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.]]

关于python - tensorflow 多项式数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55370317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com