如何使用torch.stack?

问题描述 投票:0回答:4

如何使用

torch.stack
堆叠两个形状为
a.shape = (2, 3, 4)
b.shape = (2, 3)
的张量,而不需要就地操作?

python pytorch tensor
4个回答
38
投票

堆叠需要相同数量的维度。一种方法是松开并堆叠。例如:

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

21
投票

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

我在 pytorch 1.2 和 1.4 中使用了

torch.stack
,而不是
torch.cat

>>> 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])

如果您想使用

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])

这是另一个例子:

>>> 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]]))

使用

stack
,您可以使用
dim
参数,该参数可让您指定在哪个维度上堆叠具有相同维度的张量。


5
投票

假设你有两个维度相等的张量 a, b,即 a ( A, B, C) 所以 b (A, B , C) 一个例子

a=torch.randn(2,3,4)
b=torch.randn(2,3,4)
print(a.size())  # 2, 3, 4
print(b.size()) # 2, 3, 4

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

如果它们不一样暗淡,它就不会起作用。小心!!


0
投票

使用stack(),不同大小(形状)的一维张量不能如下所示连接。 *张量的大小(形状)必须相同:

import torch

tensor1 = torch.tensor([2, 3, 4]) # The size is [3].
tensor2 = torch.tensor([2, 3]) # The size is [2].

torch.stack(tensors=(tensor1, tensor2)) # Error

运行时错误:堆栈期望每个张量大小相等,但在条目 0 处得到 3,在条目 1 处得到 2

在您的情况下,可以使用

cat()concat(),如下所示:

*备注:

    使用
  • cat()
    concat()
    ,除一维张量外,张量的大小(形状)必须相同。
  • concat()
    cat()
     的别名。
import torch tensor1 = torch.tensor([2, 3, 4]) # The size is [3]. tensor2 = torch.tensor([2, 3]) # The size is [2]. torch.cat(tensors=(tensor1, tensor2)) torch.concat(tensors=(tensor1, tensor2)) # tensor([2, 3, 4, 2, 3])
    
© www.soinside.com 2019 - 2024. All rights reserved.