Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical AND/OR in Keras Backend

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.

like image 272
dashnick Avatar asked Apr 20 '18 21:04

dashnick


2 Answers

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.

like image 89
Baruch Youssin Avatar answered Sep 22 '22 00:09

Baruch Youssin


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?

like image 28
Daniel Möller Avatar answered Sep 21 '22 00:09

Daniel Möller