unsqueeze()

官方解释: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])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值