Mr.TripleDouble
Mr.TripleDouble

Reputation: 137

How do you invert a tensor of boolean values in Pytorch?

With NumPy, you can do it with np.invert(array), but there's no invert function in Pytorch. Let's say I have a 2D tensor of boolean values:

import torch

ts = torch.rand((10, 4)) < .5
tensor([[ True,  True, False,  True],
        [ True,  True,  True,  True],
        [ True, False,  True,  True],
        [False,  True,  True, False],
        [False,  True,  True,  True],
        [ True,  True,  True,  True],
        [ True, False,  True,  True],
        [False,  True, False,  True],
        [ True,  True, False,  True],
        [False, False,  True, False]])

How do I transform the False into True and vice versa?

Upvotes: 13

Views: 23873

Answers (1)

Nicolas Gervais
Nicolas Gervais

Reputation: 36594

Literally just use the tilde to transform all True into False and vice versa.

ts = ~ts

Upvotes: 35

Related Questions