Python 如何使用 torch.stack 功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52288635/
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:04:06  来源:igfitidea点击:

How to use torch.stack function

pythonpytorchtensor

提问by ???

I have a question about torch.stack

我有一个关于 torch.stack 的问题

I have 2 tensors, a.shape=(2, 3, 4) and b.shape=(2, 3). How to stack themwithout in-place operation?

我有 2 个张量,a.shape=(2, 3, 4) 和 b.shape=(2, 3)。 如何在没有就地操作的情况下堆叠它们

回答by arjoonn

Stacking requires same number of dimensions. One way would be to unsqueeze and stack. For example:

堆叠需要相同数量的维度。一种方法是解压和堆叠。例如:

a.size()  # 2, 3, 4
b.size()  # 2, 3
b = torch.unsqueeze(b, dim=2)  # 2, 3, 1
# torch.unsqueeze(b, dim=-1) does the same thing

torch.stack([a, b], dim=2)  # 2, 3, 5

回答by gil.fernandes

Using pytorch 1.2 or 1.4 arjoonn's answer did not work for me.

使用 pytorch 1.2 或 1.4 arjoonn 的答案对我不起作用。

Instead of torch.stackI have used torch.catwith pytorch 1.2 and 1.4:

而不是torch.stack我使用torch.catpytorch 1.2 和 1.4:

>>> import torch
>>> a = torch.randn([2, 3, 4])
>>> b = torch.randn([2, 3])
>>> b = b.unsqueeze(dim=2)
>>> b.shape
torch.Size([2, 3, 1])
>>> torch.cat([a, b], dim=2).shape
torch.Size([2, 3, 5])

If you want to use torch.stackthe dimensions of the tensors have to be the same:

如果要使用torch.stack张量的尺寸必须相同:

>>> a = torch.randn([2, 3, 4])
>>> b = torch.randn([2, 3, 4])
>>> torch.stack([a, b]).shape
torch.Size([2, 2, 3, 4])

Here is another example:

这是另一个例子:

>>> t = torch.tensor([1, 1, 2])
>>> stacked = torch.stack([t, t, t], dim=0)
>>> t.shape, stacked.shape, stacked

(torch.Size([3]),
 torch.Size([3, 3]),
 tensor([[1, 1, 2],
         [1, 1, 2],
         [1, 1, 2]]))

With stackyou have the dimparameter which lets you specify on which dimension you stack the tensors with equal dimensions.

有了stack这个dim参数,您就可以指定在哪个维度上堆叠具有相同维度的张量。