将参数输入张量流中的占位符

Feeding parameters into placeholders in tensorflow

我正在尝试进入 tensorflow,建立一个网络,然后向它提供数据。出于某种原因,我得到了错误消息 ValueError: setting an array element with a sequence。我做了一个我正在尝试做的最小例子:

import tensorflow as tf
K = 10

lchild = tf.placeholder(tf.float32, shape=(K))
rchild = tf.placeholder(tf.float32, shape=(K))
parent = tf.nn.tanh(tf.add(lchild, rchild))

input = [ tf.Variable(tf.random_normal([K])),
          tf.Variable(tf.random_normal([K])) ]

with tf.Session() as sess :
    print(sess.run([parent], feed_dict={ lchild: input[0], rchild: input[1] }))

基本上,我正在建立一个包含占位符和一系列我想学习的输入嵌入的网络,然后我尝试 运行 网络,将输入嵌入输入其中。通过搜索错误消息可以看出,我的 feed_dict 可能有问题,但我在 eg 中看不到任何明显的不匹配。维度。

那么,我错过了什么,或者我是如何完全倒退的?

编辑:我编辑了上面的内容以阐明输入表示需要学习的嵌入。我想这个问题可以问得更尖锐:Is it possible to use placeholders for parameters?

输入应该是 numpy 数组。

所以,不用 tf.Variable(tf.random_normal([K])),只需写 np.random.randn(K),一切都应该按预期工作。

编辑(我回答后问题得到澄清):

可以使用占位符作为参数,但方式略有不同。例如:

lchild = tf.placeholder(tf.float32, shape=(K))
rchild = tf.placeholder(tf.float32, shape=(K))
parent = tf.nn.tanh(tf.add(lchild, rchild))
loss = <some loss that depends on the parent tensor or lchild/rchild>
# Compute gradients with respect to the input variables
grads = tf.gradients(loss, [lchild, rchild])

inputs = [np.random.randn(K), np.random.randn(K)]
for i in range(<number of iterations>):
    np_grads = sess.run(grads, feed_dict={lchild:inputs[0], rchild:inputs[1])
    inputs[0] -= 0.1 * np_grads[0]
    inputs[1] -= 0.1 * np_grads[1]

但这不是最好或最简单的方法。它的主要问题是,在每次迭代中,您都需要在会话内外复制 numpy 数组(运行 可能在不同的设备上,如 GPU)。

占位符通常用于提供模型外部的数据(如文本或图像)。使用 tensorflow 实用程序解决它的方法类似于:

lchild = tf.Variable(tf.random_normal([K])
rchild = tf.Variable(tf.random_normal([K])
parent = tf.nn.tanh(tf.add(lchild, rchild))
loss = <some loss that depends on the parent tensor or lchild/rchild>
train_op = tf.train.GradientDescentOptimizer(loss).minimize(0.1)

for i in range(<number of iterations>):
    sess.run(train_op)

# Retrieve the weights back to numpy:
np_lchild = sess.run(lchild)