Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting values in multiple indices from a tensor at once, in tensorflow

Let's consider a numpy matrix, o:

If we want to use the following function by using numpy:

o[np.arange(x), column_array]

I can get multiple indices from a numpy array at once.

I have tried to do the same with tensorflow, but it doesn't work as what I have done. When o is a tensorflow tensor;

o[tf.range(0, x, 1), column_array]

I get the following error:

TypeError: can only concatenate list (not "int") to list

What can I do?

like image 527
yusuf Avatar asked May 05 '17 07:05

yusuf


People also ask

Can we have multidimensional tensor?

Tensors are multi-dimensional arrays with a uniform type (called a dtype ). You can see all supported dtypes at tf. dtypes.

Can you index tensors?

Single element indexing for a 1-D tensors works mostly as expected. Like R, it is 1-based. Unlike R though, it accepts negative indices for indexing from the end of the array. (In R, negative indices are used to remove elements.)

How do you subset a tensor?

Basically to subset a tensor for some indexes [a,b,c] It needs to get in the format [[0,a],[1,b],[2,c]] and then use gather_nd() to get the subset.

How do you slice in TensorFlow?

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.


1 Answers

You can try tf.gather_nd(), as How to select rows from a 3-D Tensor in TensorFlow? this post suggested. Here is an example for getting multiple indices from matrix o.

o = tf.constant([[1, 2, 3, 4],
                 [5, 6, 7, 8],
                 [9, 10, 11, 12],
                 [13, 14, 15, 16]])
# [row_index, column_index], I don’t figure out how to
# combine row vector and column vector into this form.
indices = tf.constant([[0, 0], [0, 1], [2, 1], [2, 3]])

result = tf.gather_nd(o, indices)

with tf.Session() as sess:
    print(sess.run(result)) #[ 1  2 10 12]
like image 157
Hui.X Avatar answered Oct 02 '22 02:10

Hui.X