如何在 PyTorch 中将张量大小从 [a, b] 转换为 [a, b, k]

时间:2021-03-01 12:19:35

标签: pytorch tensor

我想为张量添加一个额外的维度并将该维度的值设置为特定值。
例如,

int
print(a.size)
torch.Size([10, 5])
# after tranformation and set a to b
print(b.size)
torch.Size([10, 5, 1])

提前感谢。

2 个答案:

答案 0 :(得分:3)

torch.stack 允许您沿新维度连接两个数组

value = 1.37
a = torch.normal(0, 1, size=(5, 10))
c = torch.stack([a, torch.ones(a.shape) * value], dim=1)
c.shape

Out: torch.Size([5, 2, 10])
c[:, 0, :]

Out: tensor([[-0.2944, -0.7366,  0.6882, -0.7106,  0.0182, -0.1156, -1.0394, -0.7524,
          0.7587, -0.6066],
        [-1.0445, -2.7990,  0.0232,  0.5246, -0.7383,  0.0306, -1.0277, -0.8969,
          0.4026,  0.2006],
        [-1.2622, -0.6563, -1.9218, -0.6932, -1.9633,  1.8271,  0.6753, -0.7564,
          0.0107, -0.2312],
        [-0.8111, -1.0776, -0.8583,  0.2782, -0.8116,  0.0984,  0.4799,  0.6854,
          0.4408, -0.4280],
        [-1.1083,  1.8509,  0.1209,  0.5571, -1.1472,  0.2342,  0.3912,  0.7858,
          0.5879,  0.4139]])

c[:, 1, :]

Out: tensor([[1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700,
         1.3700],
        [1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700,
         1.3700],
        [1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700,
         1.3700],
        [1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700,
         1.3700],
        [1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700, 1.3700,
         1.3700]])

答案 1 :(得分:2)

问题的第一部分可以用unsqueeze

解决
a.shape
>>>torch.Size([10, 5])

a.unsqueeze(2).shape
>>>torch.Size([10, 5, 1]))

您也可以使用 a.unsqueeze(-1) 在最后一个维度上添加维度,但最好使用 2,如 The Zen of Python:显式优于隐式。