torch.squeeze和 unsqueeze

squeeze

官方解释:

在这里插入图片描述

Docstring:
squeeze(input, dim=None, *, out=None) -> Tensor

Returns a tensor with all the dimensions of :attr:`input` of size `1` removed.(默认情况下,返回的是将所有的1维的都去掉的一个tensor)

For example, if `input` is of shape:
:math:`(A \times 1 \times B \times C \times 1 \times D)` then the `out` tensor
will be of shape: :math:`(A \times B \times C \times D)`.(如果给定了维度,则会去掉指定的所有的维度,dim=0是不做修改,dim=1则会将第一个1维的去掉)

When :attr:`dim` is given, a squeeze operation is done only in the given
dimension. If `input` is of shape: :math:`(A \times 1 \times B)`,
``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)``
will squeeze the tensor to the shape :math:`(A \times B)`.

.. note:: The returned tensor shares the storage with the input tensor,
          so changing the contents of one will change the contents of the other.(注意:返回的tensor是和输入的Tensor共享存储的。所以改变一个就会改变其他的)

.. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)`
          will also remove the batch dimension, which can lead to unexpected
          errors.(警告:如果输入的tensor有多个1维的则经过squeeze(input)后会去掉所有的1维度,所以使用的时候要特别注意,稍有不慎,可能会发生意想不到的错误)

Args:
    input (Tensor): the input tensor.
    dim (int, optional): if given, the input will be squeezed only in
           this dimension

Keyword args:
    out (Tensor, optional): the output tensor.

官方的例子:

在这里插入图片描述

实现细节

在这里插入图片描述

默认去掉所有的1维的,如果是0则表示啥也不操作

在这里插入图片描述

去掉第一个1维的(但是如果是2则会出问题待解决)

在这里插入图片描述

unsqueeze的用法

直接看官方的实例

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值