pytorch中的torch.squeeze()函数

139 阅读1分钟

官方文档

torch.squeeze(*input*, *dim=None*) → [Tensor]
  • 参数

    • input (Tensor) – the input tensor.

    • dim (int or tuple of ints , optional) –

      • 如果给定,输入将被挤压,仅在指定的尺寸。

功能是维度压缩,返回一个张量,删除大小为1的所有指定输入维度。

举个例子:如果 input 的形状为 (A×1×B×C×1×D),那么返回的tensor的形状则为 (A×B×C×D)

当给定 dim 时,那么只在给定的维度(dimension)上进行压缩操作。

举个例子:如果 input 的形状为 (A×1×B),squeeze(input, 0)后,返回的tensor不变;squeeze(input, 1)后,返回的tensor将被压缩为 (A×B)

例子

>>> x = torch.zeros(2, 1, 2, 1, 2)
>>> x.size()
torch.Size([2, 1, 2, 1, 2])
>>> y = torch.squeeze(x)
>>> y.size()
torch.Size([2, 2, 2])
>>> y = torch.squeeze(x, 0)
>>> y.size()
torch.Size([2, 1, 2, 1, 2])
>>> y = torch.squeeze(x, 1)
>>> y.size()
torch.Size([2, 2, 1, 2])
>>> y = torch.squeeze(x, (1, 2, 3))
torch.Size([2, 2, 2])