How to get specific rows of a tensor in TensorFlow?

by coty_beier , in category: General Help , 6 months ago

How to get specific rows of a tensor in TensorFlow?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by emerald.wunsch , 6 months ago

@coty_beier 

To get specific rows of a tensor in TensorFlow, you can use the indexing capabilities of TensorFlow. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import tensorflow as tf

# Create a tensor
tensor = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Get specific rows
rows = tf.constant([0, 2])  # Rows 0 and 2
selected_rows = tf.gather(tensor, rows)

# Run the session
with tf.Session() as sess:
    result = sess.run(selected_rows)
    print(result)


Output:

1
2
[[1 2 3]
 [7 8 9]]


In this example, tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) creates a 3x3 tensor. tf.constant([0, 2]) specifies the rows to select, and tf.gather(tensor, rows) selects those rows from the tensor. The result is evaluated using a session and printed.


Note that indexing in TensorFlow starts from 0. If you want to select multiple non-consecutive rows, you can provide a list of row indices in the rows tensor.

Member

by jewel , 2 months ago

@coty_beier 

If you want to select specific rows based on conditions, you can use TensorFlow's boolean masking technique. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import tensorflow as tf

# Create a tensor
tensor = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Create a boolean mask based on condition
condition = tf.constant([True, False, True])  # Select rows 0 and 2 based on this mask
mask = tf.cast(condition, tf.float32)

# Apply mask to select specific rows
selected_rows = tf.boolean_mask(tensor, mask)

# Run the session
with tf.Session() as sess:
    result = sess.run(selected_rows)
    print(result)


Output:

1
2
[[1 2 3]
 [7 8 9]]


In this example, tf.constant([True, False, True]) creates a boolean mask where True indicates the rows to be selected. The tf.cast function is used to convert the boolean mask to float32 for compatibility with tf.boolean_mask. Finally, tf.boolean_mask(tensor, mask) applies the mask to select the specific rows from the tensor.