Reputation: 3781
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?
Upvotes: 5
Views: 5142
Reputation: 136
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]
Upvotes: 5
Reputation: 2732
You may want to see tf.gather_nd
: https://www.tensorflow.org/api_docs/python/tf/gather_nd
import tensorflow as tf
import numpy as np
tensor = tf.placeholder(tf.float32, [2,2])
indices = tf.placeholder(tf.int32, [2,2])
selected = tf.gather_nd(tensor, indices=indices)
with tf.Session() as session:
data = np.array([[0.1,0.2],[0.3,0.4]])
idx = np.array([[0,0],[1,1]])
result = session.run(selected, feed_dict={indices:idx, tensor:data})
print(result)
and the result will be [ 0.1 0.40000001]
Upvotes: 1