TensorFlow:使用张量索引另一个张量

TensorFlow: using a tensor to index another tensor

我有一个关于如何在 TensorFlow 中进行索引的基本问题。

在 numpy 中:

x = np.asarray([1,2,3,3,2,5,6,7,1,3])
e = np.asarray([0,1,0,1,1,1,0,1])
#numpy 
print x * e[x]

我可以得到

[1 0 3 3 0 5 0 7 1 3]

如何在 TensorFlow 中执行此操作?

x = np.asarray([1,2,3,3,2,5,6,7,1,3])
e = np.asarray([0,1,0,1,1,1,0,1])
x_t = tf.constant(x)
e_t = tf.constant(e)
with tf.Session():
    ????

谢谢!

幸运的是,tf.gather():

在 TensorFlow 中支持您所询问的确切情况
result = x_t * tf.gather(e_t, x_t)

with tf.Session() as sess:
    print sess.run(result)  # ==> 'array([1, 0, 3, 3, 0, 5, 0, 7, 1, 3])'

tf.gather() 操作不如 NumPy's advanced indexing: it only supports extracting full slices of a tensor on its 0th dimension. Support for more general indexing has been requested, and is being tracked in this GitHub issue 强大。