连接 3 维张量(张量重塑)

Concatination on a 3 dimensional tensor (Tensor Re-Shaping)

我有2个张量,

他们的格式目前分别是[13, 2]。我正在尝试将两者组合成一个尺寸为 [2, 13, 2] 的 3 维张量,以便它们彼此堆叠,但是被分成批次。

这是格式 [13, 2] 中的张量之一的示例:

tensor([[[-1.8588,  0.3776],
         [ 0.1683,  0.2457],
         [-1.2740,  0.5683],
         [-1.7262,  0.4350],
         [-1.7262,  0.4350],
         [ 0.1683,  0.2457],
         [-1.0160,  0.5940],
         [-1.3354,  0.5565],
         [-0.7497,  0.5792],
         [-0.2024,  0.4251],
         [ 1.0791, -0.2770],
         [ 0.3032,  0.1706],
         [ 0.8681, -0.1607]])

我想保持形状,但将它们分成两组,使用相同的张量。下面是我所追求的格式示例:

tensor([[[-1.8588,  0.3776],
         [ 0.1683,  0.2457],
         [-1.2740,  0.5683],
         [-1.7262,  0.4350],
         [-1.7262,  0.4350],
         [ 0.1683,  0.2457],
         [-1.0160,  0.5940],
         [-1.3354,  0.5565],
         [-0.7497,  0.5792],
         [-0.2024,  0.4251],
         [ 1.0791, -0.2770],
         [ 0.3032,  0.1706],
         [ 0.8681, -0.1607]],

         [[-1.8588,  0.3776],
         [ 0.1683,  0.2457],
         [-1.2740,  0.5683],
         [-1.7262,  0.4350],
         [-1.7262,  0.4350],
         [ 0.1683,  0.2457],
         [-1.0160,  0.5940],
         [-1.3354,  0.5565],
         [-0.7497,  0.5792],
         [-0.2024,  0.4251],
         [ 1.0791, -0.2770],
         [ 0.3032,  0.1706],
         [ 0.8681, -0.1607]]])

有人知道如何使用串联来做到这一点吗?我曾尝试在使用 torch.cat((a, b.unsqueeze(0)), dim=-1) 时使用 .unsqueeze,但是它将格式更改为 [13, 4, 1],这不是我想要的格式。

下面的解决方案有效,但是,我的想法是我会通过循环不断堆叠到 y 而不受形状的限制。对不起,我的想法不够清楚。

它们的大小都是 [13,2],所以它会以 [1,13,2]、[2,13,2]、[3,13,2]、[ 4,13,2] 等等...

在这种情况下,你需要torch.stack而不是torch.cat,至少它更方便:

x1 = torch.randn(13,2)
x2 = torch.randn(13,2)
y = torch.stack([x1,x2], 0) # creates a new dimension 0
print(y.shape)
>>> (2, 13, 2)

虽然您确实可以使用 unsqueezecat,但是您需要解压缩两个输入张量:

x1 = torch.randn(13,2).unsqueeze(0) # shape: (1,13,2)
x2 = torch.randn(13,2).unsqueeze(0) # same
y = torch.cat([x1, x2], 0)
print(y.shape)
>>> (2,13,2)

这里有一个有用的线程来理解差异:

如果你需要堆叠更多的张量,其实并没有多难,堆叠适用于任意数量的张量:

# This list of tensors is what you will build in your loop
tensors = [torch.randn(13, 2) for i in range(10)]
# Then at the end of the loop, you stack them all together
y = torch.stack(tensors, 0)
print(y.shape)
>>> (10, 13, 2)

或者,如果您不想使用该列表:

# first, build the y tensor to which the other ones will be appended
y = torch.empty(0, 13, 2)
# Then the loop, and don't forget to unsqueeze
for i in range(10):
    x = torch.randn(13, 2).unsqueeze(0)
    y = torch.cat([y, x], 0)

print(y.shape)
>>> (10, 13, 2)