#【PyTorch】squeeze函数详解

函数原型

torch.squeeze(input, dim=None, *, out=None) → Tensor

函数详解

删除一个张量中所有维数为1的维度

例如,一个维度为 ( A × 1 × B × C × 1 × D ) (A \times 1 \times B \times C \times 1 \times D) (A×1×B×C×1×D)的张量调用squeeze方法后维度变为 ( A × B × C × D ) (A \times B \times C \times D) (A×B×C×D)

当给定dim参数后,squeeze操作只作用于给定维度。如果输入input的形状为 ( A × 1 × B ) (A \times 1 \times B) (A×1×B), squeeze(input, 0)不改变这个张量, 但是squeeze(input, 1) 将把这个张量的形状变为 ( A × B ) (A \times B) (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])

————文章内容翻译自[PyTorch官方文档](https://pytorch.org/docs/stable/generated/torch.squeeze.html?highlight=squeeze#torch.squeeze)
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐