Given an array and mask of same shapes, I want the masked output of the same shape and containing 0 where mask is False.
For example,
# input array
img = torch.randn(2, 2)
print(img)
# tensor([[0.4684, 0.8316],
# [0.8635, 0.4228]])
print(img.shape)
# torch.Size([2, 2])
# mask
mask = torch.BoolTensor(2, 2)
print(mask)
# tensor([[False, True],
# [ True, True]])
print(mask.shape)
# torch.Size([2, 2])
# expected masked output of shape 2x2
# tensor([[0, 0.8316],
# [0.8635, 0.4228]])
Issue: The masking changes the shape of the output as follows:
#1: shape changed
img[mask]
# tensor([0.8316, 0.8635, 0.4228])
To get the shape of a tensor as a list in PyTorch, we can use two approaches. One using the size() method and another by using the shape attribute of a tensor in PyTorch.
Returns the value of this tensor as a standard Python number. This only works for tensors with one element.
It'll modify the tensor metadata and will not create a copy of it.
Simply type-cast your boolean mask to an integer mask, followed by float to bring the mask to the same type as in img
. Perform element-wise multiplication afterwards.
masked_output = img * mask.int().float()
One of the ways I found to solve it was:
img[mask==False] = 0
or using
img[~mask] = 0
It'll change the img
itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With