官方解释: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. A :attr:`dim` value within the range ``[-input.dim() - 1, input.dim() + 1)`` can be used. Negative :attr:`dim` will correspond to :meth:`unsqueeze` applied at :attr:`dim` = ``dim + input.dim() + 1``.
简单理解就是在指定维度上增加维度。
实例:
import torch
# 创建一个一维数组
x = torch.tensor([1, 2, 3, 4])
print(x)
print(x.shape)
# 使用unsqueeze在第0维(即最前面)增加一个维度
x_unsqueezed = x.unsqueeze(0)
print(x_unsqueezed)
print(x_unsqueezed.shape)
# 使用unsqueeze在第1维增加一个维度
x_unsqueezed1 = torch.unsqueeze(x,dim=1)
print(x_unsqueezed1)
print(x_unsqueezed1.shape)
输出:此处1:2:3:4:为自己标记方便理解
#原
tensor([1, 2, 3, 4])
torch.Size([4])#第0维增加
tensor([1:[1, 2, 3, 4]])
torch.Size([1, 4])#第1维增加
tensor([1:[1],
2:[2],
3: [3],
4:[4]])
torch.Size([4, 1])