简体   繁体   中英

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 ie 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, :] ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM