MCPcopy Create free account
hub / github.com/google-research/language / where

Function where

language/common/utils/tensor_utils.py:50–98  ·  view source on GitHub ↗

Selects slices of `if_true` and `if_false` based on `condition`. This is a wrapper around tf.where() that allows it to select slices at any level of a tensor. (Recall that tf.where() can only select slices on the first axis or select individual elements). Example usage: condition = tf.

(condition, if_true, if_false)

Source from the content-addressed store, hash-verified

48
49
50def where(condition, if_true, if_false):
51 """Selects slices of `if_true` and `if_false` based on `condition`.
52
53 This is a wrapper around tf.where() that allows it to select slices at any
54 level of a tensor. (Recall that tf.where() can only select slices on the
55 first axis or select individual elements).
56
57 Example usage:
58
59 condition = tf.constant([[True, False],
60 [False, True]])
61 if_true = tf.constant([[[1, 1], [2, 2]],
62 [[3, 3], [4, 4]]])
63 if_false = tf.constant([[[5, 5], [6, 6]],
64 [[7, 7], [8, 8]]])
65
66 result = where(condition, if_true, if_false)
67
68 assert result.eval() == [[[1, 1], [6, 6]],
69 [[7, 7], [4, 4]]]
70
71 Args:
72 condition: <bool>[...] Condition for selecting slices.
73 if_true: <T>[condition.shape, ...] Values to use if `condition` is true.
74 if_false: <T>[condition.shape, ...] Values to use if `condition` is false.
75
76 Returns:
77 <T>[if_true.shape] Values after conditional selection.
78 """
79 # TODO(terrykoo): Rewrite when tf.where() supports broadcasting: b/78594182.
80 condition_rank = condition.shape.ndims
81 result_rank = if_true.shape.ndims
82
83 # Use tf.where() directly if it can handle the args.
84 if condition_rank == 1 or condition_rank == result_rank:
85 return tf.where(condition, if_true, if_false)
86
87 result_dims = shape(if_true)
88 inner_dims = result_dims[condition_rank:]
89
90 # Flatten outer dims so we can select slices on axis=0.
91 condition = tf.reshape(condition, [-1])
92 if_true = tf.reshape(if_true, [-1] + inner_dims)
93 if_false = tf.reshape(if_false, [-1] + inner_dims)
94
95 result = tf.where(condition, if_true, if_false)
96
97 # Restore original shape.
98 return tf.reshape(result, result_dims)
99
100
101def padded_where(condition, length):

Callers

nothing calls this directly

Calls 1

shapeFunction · 0.70

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…