我想使用 TensorFlow 来训练一些潜在的(直到运行时才可用)变量。我收到以下错误:“ValueError:使用序列设置数组元素。”
如果我用常量值初始化“a”,我可以获得预期的结果,但我的应用程序不允许在运行时之前知道“a”的值,并且我打算在运行后使用梯度下降来优化它们他们变得可用。看起来“占位符”提供了此功能,但我显然需要一些帮助才能正确使用它们。我想知道将潜在变量输入 TensorFlow 图中的正确方法。这是一个简化的重现:
import tensorflow as tf
import numpy as np
a = tf.placeholder(tf.float64, [2, 1])
b = tf.Variable(np.array([[1., 3.]]))
c = tf.matmul(a, b)
latent = tf.Variable(np.array([[2.],[3.]]))
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
print(sess.run(c, feed_dict={a: latent}))
预期结果: [[ 2. 6.] [ 3. 9.]]
实际结果: ValueError:使用序列设置数组元素。
最佳答案
您可以做两件事。您可以从占位符初始化变量,并将其初始化为提供给该占位符的值。
import tensorflow as tf
latent_init_val = tf.placeholder(tf.float64, [1, 2])
latent = tf.Variable(latent_init_val)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op, feed_dict={latent_init_val: [[2., 3.]]})
或者您可以简单地使用load
变量的方法来设置其值,而无需使用任何其他对象。
import tensorflow as tf
# Initial value only matters for shape here
latent = tf.Variable([[0., 0.]], dtype=tf.float64)
with tf.Session() as sess:
latent.load([[2., 3.]], sess)
关于python - 如何将潜在变量输入 TensorFlow 图中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55749195/