Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert boolean tensor to binary in tensorflow

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?

like image 903
Edv Beq Avatar asked Jun 10 '26 06:06

Edv Beq


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)
like image 74
Edv Beq Avatar answered Jun 15 '26 00:06

Edv Beq


For people who need literally what the question asked:

tf.where(r, 1, 0)

where r is your boolean tensor

like image 26
Algorithmic Canary Avatar answered Jun 15 '26 00:06

Algorithmic Canary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!