2 回答

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

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.]]
添加回答
举报