如何将潜在变量输入TensorFlow图?

问题描述 投票:2回答:2

我想使用TensorFlow训练一些潜在的(直到运行时不可用)变量。我收到以下错误:“ValueError:设置一个带序列的数组元素。”

如果我使用常量值初始化'a',我可以获得预期的结果,但是我的应用程序不允许在运行时之前知道'a'的值,并且我打算在它们可用之后使用渐变下降来优化它们。看起来“占位符”提供了这个功能,但我显然需要一些正确使用它们的帮助。我想知道将潜在变量提供给TensorFlow图的正确方法。这是一个简化的repro:

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:使用序列设置数组元素。

python variables tensorflow placeholder
2个回答
3
投票

你可以做两件事。您可以从占位符初始化变量,并将其初始化为馈送到该占位符的值。

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)

1
投票

试试这个:

feed_dict = {a: np.array([[2.],[3.]])}

您无法提供变量/张量。相反,您可以先评估变量的值,然后将其提供给占位符。

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)
    latent_val = latent.eval() # <-- evaluate the value of the variable
    print(sess.run(c, feed_dict={a: latent_val}))
    # [[2. 6.]
    #  [3. 9.]]
© www.soinside.com 2019 - 2024. All rights reserved.