Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trim / remove part of a Tensor to match the shape of another Tensor with PyTorch?

I have 2 tensors:

outputs: torch.Size([4, 27, 161])       pred: torch.Size([4, 30, 161])

I want to cut pred (from the end) so that it'll have the same dimensions as outputs.

What's the best way to do it with PyTorch?

like image 356
Shamoon Avatar asked Apr 09 '20 13:04

Shamoon


People also ask

How do you cut a tensor PyTorch?

Slicing a 3D Tensor Slicing: Slicing means selecting the elements present in the tensor by using “:” slice operator. We can slice the elements by using the index of that particular element. Parameters: tensor_position_start: Specifies the Tensor to start iterating.

What is squeeze and Unsqueeze in PyTorch?

squeeze(input). It squeezes (removes) the size 1 and returns a tensor with all other dimensions of the input tensor. Compute torch. unsqueeze(input, dim). It inserts a new dimension of size 1 at the given dim and returns the tensor.

What does padding do in PyTorch?

Constant padding is implemented for arbitrary dimensions. Replicate and reflection padding are implemented for padding the last 3 dimensions of a 4D or 5D input tensor, the last 2 dimensions of a 3D or 4D input tensor, or the last dimension of a 2D or 3D input tensor.


1 Answers

You can use Narrow

e.g:

a = torch.randn(4,30,161)
a.size() # torch.Size([4, 30, 161])
a.narrow(1,0,27).size() # torch.Size([4, 27, 161])
like image 84
Felipe Curti Avatar answered Nov 14 '22 23:11

Felipe Curti