27

I have a basic question about how to do indexing in TensorFlow.

In 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]

I can get

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

How can I do this in 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():
    ????

Thanks!

1

1 Answer 1

36

Fortunately, the exact case you're asking about is supported in TensorFlow by tf.gather():

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])'

The tf.gather() op is less powerful than 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.

Sign up to request clarification or add additional context in comments.

2 Comments

Tensorflow now has a more powerful tf.gather_nd() op.
Also, tf.gather now supports any axis, not only the 0th dimension, with the argument axis.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.