Convert boolean tensor to binary in tensorflow

Viewed 1187

I have an Boolean tensor and I want to convert to a binary tensor of ones and zeros.

To put it into context - I have the following tensor

[[ True False  True]
 [False  True False]
 [ True False  True]]

which I need to turn into ones and zeros so then I can multiply element wise with a value tensor, i.e.:

[[1.         0.64082676 0.90568966]
 [0.64082676 1.         0.37999165]
 [0.90568966 0.37999165 1.        ]]

I tried both these functions

   masks = tf.map_fn(logical, masks, dtype=tf.float32)
   masks = tf.vectorized_map(logical, masks)

with

@tf.function
def logical(x):
    if tf.equal(x, True):
        return zero
    return one

but unfortunately no luck. I also tried to multiply directly with the Boolean tensor but that was not allowed.

So any guidance on how to resolve this?

2 Answers

I think I solved it using this and some magic. Let penalties be the value tensor

test = tf.where(masks, penalties * 0.0, penalties * 1.0)

For people who need literally what the question asked:

tf.where(r, 1, 0)

where r is your boolean tensor

Related