I have a boolean mask in tensorflow and only want to keep the last True per line, how to…
- User
I have a boolean mask in tensorflow and only want to keep the last True per line, how to proceed ?
Assistant
You can use TensorFlow's tf.reduce_max() to keep only the last True per line in a boolean mask. Here's how:
import tensorflow as tf # Boolean mask mask = tf.constant([[True, False, True], [True, True, False], [False, True, True]]) # Get the last index of True per row last_true_idx = tf.reduce_max(tf.where(mask), axis=1) # Use last_true_idx to extract only the last True per row last_true = tf.gather_nd(mask, last_true_idx[:, None]) # last_true is # [[False False True] # [False False False] # [False True True]]This works as follows:
- Use tf.where to get the indices of all Trues in the mask. This gives [[0 0 2], [0 1], [1 2]]
- Use tf.reduce_max to get the last index (highest index) per row. This gives [2 1 2]
- Use tf.gather_nd to extract the values at the indices from last_true_idx. This gives the final mask with only the last True per row retained.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.