将列表输入 TensorFlow 中的 feed_dict 时发出问题
我正在尝试将列表传递到 feed_dict
,但是我在这样做时遇到了问题.说我有:
I'm trying to pass a list into feed_dict
, however I'm having trouble doing so. Say I have:
inputs = 10 * [tf.placeholder(tf.float32, shape=(batch_size, input_size))]
其中输入被输入到我想要计算的某个函数 outputs
中.因此,为了在 tensorflow 中运行它,我创建了一个会话并运行以下命令:
where inputs is fed into some function outputs
that I want to compute. So to run this in tensorflow, I created a session and ran the following:
sess.run(outputs, feed_dict = {inputs: data})
#data is my list of inputs, which is also of length 10
但我得到一个错误,TypeError: unhashable type: 'list'.
但是,我可以像这样按元素传递数据:
but I get an error, TypeError: unhashable type: 'list'.
However, I'm able to pass the data element-wise like so:
sess.run(outputs, feed_dict = {inputs[0]: data[0], ..., inputs[9]: data[9]})
所以我想知道是否有办法解决这个问题.我还尝试构建一个字典(使用 for
循环),但是这会生成一个包含单个元素的字典,它们的键是:tensorflow.python.framework.ops.Tensor at 0x107594a10
So I'm wondering if there's a way I can solve this issue. I've also tried to construct a dictionary(using a for
loop), however this results in a dictionary with a single element, where they key is:
tensorflow.python.framework.ops.Tensor at 0x107594a10
这里有两个问题导致了问题:
There are two issues that are causing problems here:
第一个问题是 Session.run()
调用只接受少量类型作为 feed_dict
的键.特别是,张量列表不支持作为键,因此您必须将每个张量作为单独的键.*一种方便的方法这样做是使用字典理解:
The first issue is that the Session.run()
call only accepts a small number of types as the keys of the feed_dict
. In particular, lists of tensors are not supported as keys, so you have to put each tensor as a separate key.* One convenient way to do this is using a dictionary comprehension:
inputs = [tf.placeholder(...), ...]
data = [np.array(...), ...]
sess.run(y, feed_dict={i: d for i, d in zip(inputs, data)})
第二个问题是 Python 中的 10 * [tf.placeholder(...)]
语法创建了一个包含十个元素的列表,其中每个元素相同张量对象(即具有相同的 name
属性,相同的 id
属性,并且如果比较列表中的两个元素,则引用相同使用 inputs[i] 是输入 [j]
).这解释了为什么当您尝试使用列表元素作为键创建字典时,您最终会得到一个包含单个元素的字典 - 因为所有列表元素都是相同的.
The second issue is that the 10 * [tf.placeholder(...)]
syntax in Python creates a list with ten elements, where each element is the same tensor object (i.e. has the same name
property, the same id
property, and is reference-identical if you compare two elements from the list using inputs[i] is inputs[j]
). This explains why, when you tried to create a dictionary using the list elements as keys, you ended up with a dictionary with a single element - because all of the list elements were identical.
要按照您的意图创建 10 个不同的占位符张量,您应该执行以下操作:
To create 10 different placeholder tensors, as you intended, you should instead do the following:
inputs = [tf.placeholder(tf.float32, shape=(batch_size, input_size))
for _ in xrange(10)]
如果您打印此列表的元素,您会看到每个元素都是一个具有不同名称的张量.
If you print the elements of this list, you'll see that each element is a tensor with a different name.
* 您现在可以将 元组 作为 feed_dict
的键传递,因为它们可能是用作字典键.
* You can now pass tuples as the keys of a feed_dict
, because these may be used as dictionary keys.