Select elements from tensor where mask is True, and pads the rest with 0. Example: tensor = [1 2 3 4 5 6 7] mask = [T T F F T T T] output = [1 2 5 6 7 0 0] Args: tensor: [batch_size, dim, ...] mask: [batch_size, dim] Returns: masked_tensor: [batch_si
(tensor, mask)
| 22 | |
| 23 | |
| 24 | def boolean_mask(tensor, mask): |
| 25 | """Select elements from tensor where mask is True, and pads the rest with 0. |
| 26 | |
| 27 | Example: |
| 28 | tensor = [1 2 3 4 5 6 7] |
| 29 | mask = [T T F F T T T] |
| 30 | output = [1 2 5 6 7 0 0] |
| 31 | |
| 32 | Args: |
| 33 | tensor: <T> [batch_size, dim, ...] |
| 34 | mask: <bool> [batch_size, dim] |
| 35 | |
| 36 | Returns: |
| 37 | masked_tensor: <T> [batch_size, dim, ...]. The first k items of row i |
| 38 | correspond to the k truthy values in row i of the mask tensor, |
| 39 | indexed into the provided tensor. |
| 40 | """ |
| 41 | batch_size = shape(mask, 0) |
| 42 | dim = shape(mask, 1) |
| 43 | |
| 44 | # Bring the coordinates of un-masked elements to the front. |
| 45 | mask = tf.cast(mask, tensor.dtype) |
| 46 | indices = tf.argsort(mask, axis=1, direction="DESCENDING", stable=True) |
| 47 | batch_indices = tf.expand_dims(tf.range(tf.shape(mask)[0]), 1) |
| 48 | batch_indices = tf.tile(batch_indices, [1, tf.shape(indices)[1]]) |
| 49 | coords = tf.stack([batch_indices, indices], axis=2) |
| 50 | |
| 51 | # Gather and zero masked elements. |
| 52 | selected_tensor = tf.gather_nd(tensor, coords) |
| 53 | selected_mask = tf.gather_nd(mask, coords) |
| 54 | reshape = [batch_size, dim] + [1] * (tensor.get_shape().ndims - 2) |
| 55 | selected_mask = tf.reshape(selected_mask, reshape) |
| 56 | masked_tensor = selected_tensor * selected_mask |
| 57 | |
| 58 | return masked_tensor |
| 59 | |
| 60 | |
| 61 | def shape(tensor, dim=None): |