【问题标题】:How to transform tensor size from [a, b] to [a, b, k] in PyTorch如何在 PyTorch 中将张量大小从 [a, b] 转换为 [a, b, k]
【发布时间】:2021-03-01 12:19:35
【问题描述】:

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

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

提前致谢。

【问题讨论】:

    标签: pytorch tensor


    【解决方案1】:

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

    【讨论】:

      【解决方案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:显式优于隐式。

      【讨论】:

        猜你喜欢
        • 2021-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        • 2011-05-30
        • 2017-01-05
        • 2012-09-03
        • 2013-07-02
        相关资源
        最近更新 更多