I have a variable that looks like
and I want to end up with the following variable
I have tried the a[a.nonzero()] if a is the input, but it only works in 1xn dims
Is there a way to do this in PyTorch?
You can do it this way:
x = torch.Tensor([[0,2,3,0,0,0,1,2], [0,0,1,3,0,0,5,0]])
y = torch.empty(0, x.size(1))
for r in x:
nz = r.nonzero().squeeze()
z = torch.zeros(r.numel() - nz.numel())
z = torch.cat((r[nz], z)).unsqueeze(0)
y = torch.cat((y, z))
I’m not sure it’s the best way to do it though, but hopefully it could be good enough for your case.