Python 在 Pytorch 中“unsqueeze”有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/57237352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:39:04  来源:igfitidea点击:

What does "unsqueeze" do in Pytorch?

pythonpytorchtorchtorchvision

提问by user6549804

I'm looking at the documentation, and here is their example. I cannot understand how this example corresponds to their explanation: "Returns a new tensor with a dimension of size one inserted at the specified position."

我正在查看文档,这是他们的示例。我无法理解这个例子如何对应他们的解释:“返回一个新的张量,其尺寸为 1,插入到指定位置。”

>>> x = torch.tensor([1, 2, 3, 4])
>>> torch.unsqueeze(x, 0)
tensor([[ 1,  2,  3,  4]])
>>> torch.unsqueeze(x, 1)
tensor([[ 1],
        [ 2],
        [ 3],
        [ 4]])

回答by norok2

If you look at the shape of the array before and after, you see that before it was (4,)and after it is (1, 4)(when second parameter is 0) and (4, 1)(when second parameter is 1). So a 1was inserted in the shape of the array at axis 0or 1, depending on the value of the second parameter.

如果查看前后数组的形状,您会看到之前(4,)和之后(1, 4)(当第二个参数为 时0)和(4, 1)(当第二个参数为 时1)。因此,根据第二个参数的值,将a1插入到轴0或处的数组形状中1

That is opposite of np.squeeze()(nomenclature borrowed from MATLAB) which removes axes of size 1(singletons).

这与np.squeeze()删除大小轴1(单例)的(从 MATLAB 借用的命名法)相反。

回答by prosti

I am not sure why PyTorch references are not mentioned here since this is PyTorch legacy.

我不知道为什么这里没有提到 PyTorch 引用,因为这是 PyTorch 的遗产。

torch.squeezeenter image description here

火炬.挤压在此处输入图片说明

torch.unsqueezeenter image description here

torch.unsqueeze在此处输入图片说明

回答by blueboy21

It indicates the position on where to add the dimension. torch.unsqueeze adds an additional dimension to the tensor. So let's say you have a tensor of shape (3), if you add a dimension at the 0 position, it will be of shape (1,3), which means 1 row and 3 columns. If you add at the 1 position, it will be (3,1), which means 3 rows and 1 column. If you have a 2D tensor of shape (2,2) add add an extra dimension at the 0 position, this will result of the tensor having a shape of (1,2,2), which means one channel, 2 rows and 2 columns. If you add at the 1 position, it will be of shape (2,1,2), so it will have 2 channels, 1 row and 2 columns. If you add it at the 2 position, the tensor will be of shape (2,2,1), which means 2 channels, 2 rows and one column.

它指示添加尺寸的位置。torch.unsqueeze 为张量增加了一个额外的维度。所以假设你有一个形状为 (3) 的张量,如果你在 0 位置添加一个维度,它的形状将是 (1,3),这意味着 1 行和 3 列。如果在 1 位置添加,它将是 (3,1),这意味着 3 行和 1 列。如果你有一个形状为 (2,2) 的二维张量,在 0 位置添加一个额外的维度,这将导致张量的形状为 (1,2,2),这意味着一个通道,2 行和 2列。如果在 1 位置添加,它将是 (2,1,2) 形状,因此它将有 2 个通道,1 行和 2 列。如果将其添加到 2 位置,则张量的形状为 (2,2,1),这意味着 2 个通道、2 行和 1 列。