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

标签 python variables tensorflow placeholder

我想使用 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/

相关文章:

java - 整数到 double 变量

python - 你如何使用 TensorFlow Graphkeys 获取所有权重?

python - 损失函数 Keras out_dim > 1

python - 如何使用 Python 列出 Azure 云存储中特定子目录内的所有 blob?

python - numpy 数组的谱质心

python - 使用 Tornado websocket 定期打乒乓球

tensorflow - 说卷积实现基于 GEMM(矩阵乘法)或基于 1x1 内核是什么意思?

python - pyconfig.h - 无法打开包含文件 : 'io.h' : No such file or directory

function - 如何在生成方程式的运算符中转换 perl 变量?

python - 不使用 if 语句生成多个变量输出