Tensorflow has tf.logical_and()
and tf.logical_or()
for comparison of two boolean tensors, i.e. tf.logical_and(x,y)==TRUE
if x==TRUE and y==TRUE
(doc). I can't find anything like this in the Keras backend though. They have keras.backend.any()
and .all()
, but this is for aggregation within a tensor, not between. I've been having to use workarounds with nested K.switch()
functions, but it is painfully inelegant.
Let x
and y
be boolean keras tensors of the same shape.
To take elementwise or, do the following:
keras.backend.any(keras.backend.stack([x, y], axis=0), axis=0)
To take elementwise and, do the following:
keras.backend.all(keras.backend.stack([x, y], axis=0), axis=0)
Here keras.backend.stack([x, y], axis=0)
stacks x and y into a new tensor with an additional dimension at number 0. After that keras.backend.any
takes a logical or along the new dimension, and keras.backend.any
takes the logical and.
My solution (perhaps not the best, because I haven't found others either), is:
A = K.cast(someBooleanTensor, K.floatx())
B = K.cast(anotherBooleanTensor, K.floatx())
A_and_B = A * B #this is also something I use a lot for gathering elements
A_or_B = 1 -((1-A)*(1-B))
But thinking about it now... I never tested python operators... perhaps they work?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With