Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between view() and unsqueeze() in Torch?

Tags:

Use of unsqueeze():

input = torch.Tensor(2, 4, 3) # input: 2 x 4 x 3 print(input.unsqueeze(0).size()) # prints - torch.size([1, 2, 4, 3]) 

Use of view():

input = torch.Tensor(2, 4, 3) # input: 2 x 4 x 3 print(input.view(1, -1, -1, -1).size()) # prints - torch.size([1, 2, 4, 3]) 

According to documentation, unsqueeze() inserts singleton dim at position given as parameter and view() creates a view with different dimensions of the storage associated with tensor.

What view() does is clear to me, but I am unable to distinguish it from unsqueeze(). Moreover, I don't understand when to use view() and when to use unsqueeze()?

Any help with good explanation would be appreciated!

like image 574
Wasi Ahmad Avatar asked Mar 17 '17 20:03

Wasi Ahmad


People also ask

What is Unsqueeze in PyTorch?

torch. unsqueeze (input, dim) → Tensor. Returns a new tensor with a dimension of size one inserted at the specified position. The returned tensor shares the same underlying data with this tensor.

What does View function do in PyTorch?

PyTorch allows a tensor to be a View of an existing tensor. View tensor shares the same underlying data with its base tensor. Supporting View avoids explicit data copy, thus allows us to do fast and memory efficient reshaping, slicing and element-wise operations.

What is the difference between View and reshape PyTorch?

The semantics of reshape() are that it may or may not share the storage and you don't know beforehand. Another difference is that reshape() can operate on both contiguous and non-contiguous tensor while view() can only operate on contiguous tensor. Also see here about the meaning of contiguous .

What does Unsqueeze mean?

unsqueeze is a method to change the tensor dimensions, such that operations such as tensor multiplication can be possible. This basically alters the dimension to produce a tensor that has a different dimension.


1 Answers

view() can only take a single -1 argument.

So, if you want to add a singleton dimension, you would need to provide all the dimensions as arguments. For e.g., if A is a 2x3x4 tensor, to add a singleton dimension, you would need to do A:view(2, 1, 3, 4).

However, sometimes, the dimensionality of the input is unknown when the operation is being used. Thus, we dont know that A is 2x3x4, but we would still like to insert a singleton dimension. This happens a lot when using minibatches of tensors, where the last dimension is usually unknown. In these cases, the nn.Unsqueeze is useful and lets us insert the dimension without explicitly being aware of the other dimensions when writing the code.

like image 147
greenberet123 Avatar answered Sep 25 '22 21:09

greenberet123