Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch specific rows from a tensor in Tensorflow?

I have a tensor defined as follows:

temp_var = tf.Variable(initial_value=np.asarray([[1, 2, 3],[4, 5, 6],[7, 8, 9],[10, 11, 12]]))

I also have an array of indexes of rows to be fetched from tensor:

idx = tf.constant([0, 2])

Now I want to take a subset of temp_var at those indexes i.e. idx

I know that to take a single index or a slice, we can do something like

temp_var[single_row_index, :]

or

temp_var[start:end, :]

But how to fetch rows indicated by idx array? Something like temp_var[idx, :] ?

like image 627
exAres Avatar asked Aug 03 '16 12:08

exAres


1 Answers

The tf.gather() op does exactly what you need: it selects rows from a matrix (or in general (N-1)-dimensional slices from an N-dimensional tensor). Here's how it would work in your case:

temp_var = tf.Variable([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]))
idx = tf.constant([0, 2])

rows = tf.gather(temp_var, idx)

init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)

print(sess.run(rows))  # ==> [[1, 2, 3], [7, 8, 9]]
like image 133
mrry Avatar answered Oct 09 '22 07:10

mrry