【问题标题】:How does one feed latent variables into a TensorFlow graph?如何将潜在变量输入 TensorFlow 图?
【发布时间】:2019-09-08 23:28:22
【问题描述】:

我想使用 TensorFlow 来训练一些潜在的(直到运行时才可用)变量。我收到以下错误:“ValueError: setting an array element with a sequence。”

如果我用常数值初始化“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: 使用序列设置数组元素。

【问题讨论】:

    标签: python variables tensorflow placeholder


    【解决方案1】:

    您可以做两件事。您可以从占位符初始化变量,并将其初始化为提供给该占位符的值。

    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
    【解决方案2】:

    试试这个:

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

    【讨论】:

    • 是的,这给出了预期的结果。不幸的是,它也使潜在的无法训练。
    • 你是对的,错过了你问题的那一部分。刚刚更新以将latent 保留为变量
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2018-06-13
    相关资源
    最近更新 更多