在张量流中将布尔张量转换为二进制

Convert boolean tensor to binary in tensorflow

我有一个布尔张量,我想转换为 1 和 0 的二进制张量。

具体来说——我有以下张量

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

我需要将其变成 1 和 0,这样我就可以将元素与值张量相乘,即:

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

这两个功能我都试过了

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

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

可惜运气不好。我还尝试直接与布尔张量相乘,但这是不允许的。

关于如何解决这个问题有什么指导吗?

我想我用这个和一些魔法解决了它。令惩罚为值张量

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

对于真正需要问题的人:

tf.where(r, 1, 0)

其中 r 是您的布尔张量