我正试图进入tensorflow,建立一个网络,然后向其提供数据.出于某种原因,我最终得到错误消息ValueError:设置一个带有序列的数组元素.我做了一个我想要做的最小例子:
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可能有问题,但我看不出任何明显的不匹配,例如.维.
那么,我错过了什么,或者我是如何完全倒退的呢?
编辑:我编辑了上面的内容,以澄清输入表示需要学习的嵌入.我想问题可以更明确地提出:是否可以使用占位符作为参数?
解决方法:
输入应该是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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。