我很抱歉是否已经问过这个问题,但是我对pytorch的挤压和不挤压感到非常困惑。我试图查看文档和其他stackoverflow问题,但我仍然不确定它的实际作用。我看过What does "unsqueeze" do in Pytorch?,但我还是不明白。
我试图通过自己在python中进行探索来理解它。我首先使用
创建了一个随机张量x = torch.rand(3,2,dtype=torch.float)
>>> x
tensor([[0.3703, 0.9588],
[0.8064, 0.9716],
[0.9585, 0.7860]])
但是无论我如何压缩,最终都会得到相同的结果:
>>> x.squeeze(0)
tensor([[0.3703, 0.9588],
[0.8064, 0.9716],
[0.9585, 0.7860]])
>>> x.squeeze(1)
tensor([[0.3703, 0.9588],
[0.8064, 0.9716],
[0.9585, 0.7860]])
>>> x.squeeze(-1)
tensor([[0.3703, 0.9588],
[0.8064, 0.9716],
[0.9585, 0.7860]])
如果现在尝试松开,则会得到以下信息,
>>> x.unsqueeze(1)
tensor([[[0.3703, 0.9588]],
[[0.8064, 0.9716]],
[[0.9585, 0.7860]]])
>>> x.unsqueeze(0)
tensor([[[0.3703, 0.9588],
[0.8064, 0.9716],
[0.9585, 0.7860]]])
>>> x.unsqueeze(-1)
tensor([[[0.3703],
[0.9588]],
[[0.8064],
[0.9716]],
[[0.9585],
[0.7860]]])
但是,如果我现在创建一个张量x = torch.tensor([1,2,3,4])
,然后尝试对其进行解压缩,那么看来1
和-1
使其成为与0
相同的列。
x.unsqueeze(0)
tensor([[1, 2, 3, 4]])
>>> x.unsqueeze(1)
tensor([[1],
[2],
[3],
[4]])
>>> x.unsqueeze(-1)
tensor([[1],
[2],
[3],
[4]])
有人可以解释张紧力和张紧力的作用吗?提供辩论0
,1
和-1
有什么区别?
简单地说,unsqueeze()
在张量中“添加”表面1
尺寸(在指定尺寸处,而squeeze
从张量中移除所有表面1
尺寸。
您应该查看张量的shape
属性以轻松查看它。最后一种情况是:
import torch
tensor = torch.tensor([1, 0, 2, 3, 4])
tensor.shape # torch.Size([5])
tensor.unsqueeze(dim=0).shape # [1, 5]
tensor.unsqueeze(dim=1).shape # [5, 1]
对于将单个样本提供给网络(这需要对第一维进行批处理非常有用,对于图像而言,它将是:
# 3 channels, 32 width, 32 height
tensor = torch.randn(3, 32, 32)
# 1 batch, 3 channels, 32 width, 32 height
tensor.unsqueeze(dim=0).shape
unsqueeze
如果您创建具有1个尺寸的tensor
,例如像这样:
# 3 channels, 32 width, 32 height and some 1 unnecessary dimensions
tensor = torch.randn(3, 1, 32, 1, 32, 1)
# 1 batch, 3 channels, 32 width, 32 height again
tensor.squeeze().unsqueeze(0) # [1, 3, 32, 32]