Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TensorFlow: using a tensor to index another tensor

Tags:

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!

like image 619
user200340 Avatar asked Mar 07 '16 11:03

user200340


People also ask

Can you slice tensors?

You can use tf. slice on higher dimensional tensors as well. You can also use tf. strided_slice to extract slices of tensors by 'striding' over the tensor dimensions.

Can we have multidimensional tensor?

Tensor is not simply a multidimensional array. Tensor is "something" which can be represented as multidimensional array. And this representation must depend in some very specific way from where you are looking at this "something".

How do you transpose in TensorFlow?

transpose(x, perm=[1, 0]) . As above, simply calling tf. transpose will default to perm=[2,1,0] . To take the transpose of the matrices in dimension-0 (such as when you are transposing matrices where 0 is the batch dimension), you would set perm=[0,2,1] .


1 Answers

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.

like image 190
mrry Avatar answered Oct 22 '22 23:10

mrry