Just to be upfront, this is basically the same question as Numpy array loss of dimension when masking, but for PyTorch tensors rather than NumPy arrays. The solution(s) to that questions, using the equivalent PyTorch function
torch.where
or masked tensors work, but I found a Google search about this for PyTorch tensors did quickly not hit upon an answer. So, I thought an equivalent StackOverflow pytorch tagged question might be useful for others!)
I have a 2D PyTorch tensor (although it could have more dimensions) to which I want to apply an equivalently shaped binary mask. However, when I apply the mask the output is just 1-dimensional. How can I keep the same dimensions as the original tensor after application of the mask?
E.g., for
import torch
x = torch.tensor([[1.0, 2.0, 8.0], [-4.0, 0.0, 3.0]])
mask = x >=2.0
print(x[mask])
tensor([2., 8., 3.])
the output is now 1D rather than 2D.