简体   繁体   English

将 boolean 张量转换为 tensorflow 中的二进制

[英]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.我有一个 Boolean 张量,我想转换为一个和零的二进制张量。

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, ie:我需要将其转换为 1 和 0,这样我就可以将元素与值张量相乘,即:

[[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.我还尝试直接与 Boolean 张量相乘,但这是不允许的。

So any guidance on how to resolve this?那么关于如何解决这个问题的任何指导?

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)

For people who need literally what the question asked:对于那些真正需要问题的人:

tf.where(r, 1, 0)

where r is your boolean tensor其中r是您的 boolean 张量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM