Back

torch.unsqueeze()解读

torch.unsqueeze()函数解读

语法

torch.unsqueeze(input, dim) --> Tensor

Parameters

  • input(Tensor) – the input tensor

  • dim(int) – the index at which to insert the singleton dimension

功能

Return a new tensor with a dimension of size one inserted at the specified position.

返回一个新的tensor,在指定的位置插入维度为1的一维。

The returned tensor shares the same underlaying data with this tensor.

返回的这一Tensor在内存中是和原Tensor共享一个内存数据的。(可以用contiguous来重新分配)

A dim value within the range [-input.dim() - 1, input.dim() + 1) can be used. Negative dim will correspond to unsqueeze() applied at dim = dim + input.dim() + 1

dim的取值范围是[-input.dim() - 1, input.dim() + 1). 负的dim值将被映射到dim + input.dim() + 1这一位置去。就相当于$-n$就是从最右往左数第$n$个位置。(-1就是最右插入的位置)

Example

>>> x = torch.tensor([1,2,3,4])
>>> print(x.shape)
torch.Size([4])
>>> y = torch.unsqueeze(x,0)
>>> print(y.shape)
torch.Size([1, 4])
>>> z = torch.unsqueeze(x,1)
>>> print(z.shape)
torch.Size([4, 1])
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy