【问题标题】:Feeding parameters into placeholders in tensorflow在张量流中将参数输入占位符
【发布时间】:2016-03-23 13:06:36
【问题描述】:

我正在尝试进入 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 可能有问题,但我看不到任何明显的不匹配,例如。维度。

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

编辑:我已经编辑了上面的内容,以澄清输入代表需要学习的嵌入。我想这个问题可以问得更尖锐:参数是否可以使用占位符?

【问题讨论】:

  • 我在类似尝试中看到的错误:“TypeError:提要的值不能是 tf.Tensor 对象。可接受的提要值包括 Python 标量、字符串、列表或 numpy ndarray。”

标签: python tensorflow


【解决方案1】:

输入应该是 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)

【讨论】:

  • 但是如果我不将它们包装在 tensorflow 中的东西中,它们是否仍会出现在计算图中,以便我可以为它们获取渐变?
  • 嗯,关于随机值/常数的梯度应该是 0,所以从梯度的角度来看,噪声是来自 tensorflow 还是 numpy 都没有关系。我想我误解了你的帖子。您需要指定哪些变量是可学习的,并使用随机值对其进行初始化,但您还需要创建某种损失函数来告诉优化器我们距离最佳结果还有多远。输入节点通常不可学习,并且损失取决于图形的输入和变量(参数)。
  • 是的,很抱歉在这一点上没有让我的最小化示例足够清楚。是的,需要学习输入变量(这就是我为它们使用 tf.Variable 的原因)。那么需要学习的参数就不能用占位符了?
  • 没错。占位符用于定义来自模型外部的信息(如批量文本或图像)。如果您没有任何此类数据要提供给模型,则不必使用 feed_dict。在你的情况下,你可以简单地写:parent = tf.nn.tanh(tf.add(input[0], input[1]))
  • 对我来说的问题是它的扩展性很差......无论如何,感谢您为我解决这个问题。您能否更新您的答案以反映讨论,以便我可以问心无愧地接受它,任何其他徘徊在同一混乱中的人都可以快速找到(无需涉足此讨论线程)。 :-) 干杯!
猜你喜欢
  • 1970-01-01
  • 2020-02-07
  • 2018-02-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
相关资源
最近更新 更多