TensorFlow - 类似 numpy 的张量索引 [英] TensorFlow - numpy-like tensor indexing
问题描述
在 numpy 中,我们可以这样做:
In numpy, we can do this:
x = np.random.random((10,10))
a = np.random.randint(0,10,5)
b = np.random.randint(0,10,5)
x[a,b] # gives 5 entries from x, indexed according to the corresponding entries in a and b
当我在 TensorFlow 中尝试类似的东西时:
When I try something equivalent in TensorFlow:
xt = tf.constant(x)
at = tf.constant(a)
bt = tf.constant(b)
xt[at,bt]
最后一行给出了Bad slice index tensor"异常.TensorFlow 似乎不支持像 numpy 或 Theano 这样的索引.
The last line gives a "Bad slice index tensor" exception. It seems TensorFlow doesn't support indexing like numpy or Theano.
有谁知道是否有一种 TensorFlow 方法可以做到这一点(通过任意值索引张量).我已经看过 tf.nn.embedding 部分,但我不确定它们是否可以用于此目的,即使可以,对于如此简单的事情来说,这也是一个巨大的解决方法.
Does anybody know if there is a TensorFlow way of doing this (indexing a tensor by arbitrary values). I've seen the tf.nn.embedding part, but I'm not sure they can be used for this and even if they can, it's a huge workaround for something this straightforward.
(现在,我将来自 x
的数据作为输入并在 numpy 中进行索引,但我希望将 x
放在 TensorFlow 中以获得更高的效率)
(Right now, I'm feeding the data from x
as an input and doing the indexing in numpy but I hoped to put x
inside TensorFlow to get higher efficiency)
推荐答案
您现在实际上可以使用 tf.gather_nd
.假设您有一个矩阵 m
,如下所示:
You can actually do that now with tf.gather_nd
. Let's say you have a matrix m
like the following:
| 1 2 3 4 |
| 5 6 7 8 |
并且您想要构建一个大小为 r
的矩阵,比方说,3x2,由 m
的元素构建,如下所示:
And you want to build a matrix r
of size, let's say, 3x2, built from elements of m
, like this:
| 3 6 |
| 2 7 |
| 5 3 |
| 1 1 |
r
的每个元素对应m
的一行和一列,可以有矩阵rows
和cols
带有这些索引(从零开始,因为我们正在编程,而不是在做数学!):
Each element of r
corresponds to a row and column of m
, and you can have matrices rows
and cols
with these indices (zero-based, since we are programming, not doing math!):
| 0 1 | | 2 1 |
rows = | 0 1 | cols = | 1 2 |
| 1 0 | | 0 2 |
| 0 0 | | 0 0 |
你可以像这样堆叠成一个 3 维张量:
Which you can stack into a 3-dimensional tensor like this:
| | 0 2 | | 1 1 | |
| | 0 1 | | 1 2 | |
| | 1 0 | | 2 0 | |
| | 0 0 | | 0 0 | |
这样就可以通过rows
和cols
从m
到r
,如下:>
This way, you can get from m
to r
through rows
and cols
as follows:
import numpy as np
import tensorflow as tf
m = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
rows = np.array([[0, 1], [0, 1], [1, 0], [0, 0]])
cols = np.array([[2, 1], [1, 2], [0, 2], [0, 0]])
x = tf.placeholder('float32', (None, None))
idx1 = tf.placeholder('int32', (None, None))
idx2 = tf.placeholder('int32', (None, None))
result = tf.gather_nd(x, tf.stack((idx1, idx2), -1))
with tf.Session() as sess:
r = sess.run(result, feed_dict={
x: m,
idx1: rows,
idx2: cols,
})
print(r)
输出:
[[ 3. 6.]
[ 2. 7.]
[ 5. 3.]
[ 1. 1.]]
这篇关于TensorFlow - 类似 numpy 的张量索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!