代码之家  ›  专栏  ›  技术社区  ›  user3668129

如何合并(cat)2个张量((14000,10,2)和(14000,10))?

  •  0
  • user3668129  · 技术社区  · 2 年前

    我有带形状的张量: (14000, 10, 2) 以及另一个具有形状的张量: (14000, 2)

    我想合并这两个张量,得到新的形状张量:

    (14000, 10, 3)
    

    例如:

    import torch
    import numpy as np
    
    x = torch.rand([14000, 10, 2])
    y = np.random.randint(2, size=14000)
    y = np.repeat(y, 10)
    y = torch.Tensor(y)
    y = y.view(14000, 10)
    

    我该怎么做?

    1 回复  |  直到 2 年前
        1
  •  1
  •   A.Mounir    2 年前

    你可以这样做,首先,展开第二个张量,使两个张量具有相同的维数。然后,使用torch.cat连接张量:

    import torch
    import numpy as np
    
    x = torch.rand([14000, 10, 2])
    y = np.random.randint(2, size=14000)
    y = np.repeat(y, 10)
    y = torch.Tensor(y)
    y = y.view(14000, 10)
    print("x shape: "+ str(x.shape))
    print("y shape: "+ str(y.shape))
    y = y.unsqueeze(-1)
    print("y shape after adding a dimension to its shape: "+ str(y.shape))
    x_y = torch.cat((x,y),-1)
    print("x and y concatenated: "+ str(x_y.shape))
    

    输出:

    x shape: torch.Size([14000, 10, 2])
    y shape: torch.Size([14000, 10])
    y shape after adding a dimension to its shape: torch.Size([14000, 10, 1])
    x and y concatenated: torch.Size([14000, 10, 3])