将参数输入到以十为单位的占位符中

2024-09-30 01:24:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

那么,我错过了什么,或者我是怎么把这件事完全颠倒过来的?在

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


Tags: 网络消息inputtftensorflowas错误with
1条回答
网友
1楼 · 发布于 2024-09-30 01:24:37

输入应该是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实用程序解决此问题的方法如下:

^{pr2}$

相关问题 更多 >

    热门问题