Shrink a tensor

Hi, I want to shrink a continuous mask tensor to half size. Is there any one-step or non-loop method to do that?

e.g, for a 1D(N*L) mask tensor:
before = tensor([[1, 1, 0, 0], [1, 1, 1, 1]], dtype=torch.uint8)
after = tensor([[1, 0], [1, 1]], dtype=torch.uint8)

Currently, I do this like below:

after = F.max_pool1d(before.unsqueeze(1).to(dtype=torch.float), kernel_size=2, stride=2, padding=1).squeeze(1).to(dtype=torch.uint8)

I still want to know if there is a better way.
Thanks for your help.


it will depend on the shrinkage method you want to use. If it’s max or mean, then maxpooling and meanpooling should be fairly efficient.
Otherwise, you can reshape your tensor using .view() in an NxL Tensor and use a reduction operation of your choise on the second dimension.

1 Like

Hi, my previous method is incorrect for the case of pooling by convolution (kernel_size=3,stride=2,padding=1).
Now I’m using index_select by two steps.

Thanks for your suggestion.