TensorFlow提供了tf.logical_and()
和tf.logical_or()
函数用于比较两个布尔张量,即当x==TRUE and y==TRUE
时,tf.logical_and(x,y)==TRUE
。(文档)。然而,在Keras后端中我找不到类似的函数。虽然它们提供了keras.backend.any()
和.all()
函数,但这只是用于张量内部的聚合,而非张量间的比较。我一直在使用嵌套的K.switch()
函数来实现,但这样做非常繁琐。
TensorFlow提供了tf.logical_and()
和tf.logical_or()
函数用于比较两个布尔张量,即当x==TRUE and y==TRUE
时,tf.logical_and(x,y)==TRUE
。(文档)。然而,在Keras后端中我找不到类似的函数。虽然它们提供了keras.backend.any()
和.all()
函数,但这只是用于张量内部的聚合,而非张量间的比较。我一直在使用嵌套的K.switch()
函数来实现,但这样做非常繁琐。
假设x
和y
是形状相同的布尔Keras张量。
要进行逐元素或操作,请执行以下操作:
keras.backend.any(keras.backend.stack([x, y], axis=0), axis=0)
keras.backend.all(keras.backend.stack([x, y], axis=0), axis=0)
这里的keras.backend.stack([x, y], axis=0)
将x和y叠加成一个新张量,该张量在第0维增加了一个额外维度。之后keras.backend.any
沿着新的维度进行逻辑或操作,并且keras.backend.all
进行逻辑与操作。
我提供的解决方案(也许不是最好的,因为我也没有找到其他的),是:
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))
但现在想想...我从未测试过Python运算符...也许它们有效呢?
raise TypeError("Using a 'tf.Tensor' as a Python 'bool' is not allowed.
。 - dashnick
keras
模型中使用tf.logical_and
,就像调用K.xxx
一样。 - pitfall