【问题标题】:How to weave a pytorch tensor如何编织 pytorch 张量
【发布时间】:2021-12-25 10:47:47
【问题描述】:

我有两个矩阵


A = torch.tensor([[1,1,1,1,1],
                  [1,1,1,1,1],
                  [1,1,1,1,1]])

B = torch.tensor([[2,2,2,2,2],
                  [2,2,2,2,2],
                  [2,2,2,2,2]]

我想以矩阵 C 的方式连接两个矩阵:

C = torch.tensor([[1,2,1,2,1,2,1,2],
                  [1,2,1,2,1,2,1,2],
                  [1,2,1,2,1,2,1,2]])

我认为如果 A 转换为:

 torch.tensor([[1,0,1,0,1,0,1,0],
               [1,0,1,0,1,0,1,0],
               [1,0,1,0,1,0,1,0]])

和 B 转换为:

torch.tensor([[0,2,0,2,0,2,0,2],
              [0,2,0,2,0,2,0,2],
              [0,2,0,2,0,2,0,2]])

然后将它们相加。有什么办法吗?提前致谢

【问题讨论】:

    标签: numpy pytorch data-science data-manipulation tensor


    【解决方案1】:

    您可以通过转置、堆栈和转置的组合来实现此目的:

    1. 堆栈转置张量:

      >>> torch.stack((A.T, B.T), 1)
      tensor([[[1, 1, 1],
               [2, 2, 2]],
      
              [[1, 1, 1],
               [2, 2, 2]],
      
              [[1, 1, 1],
               [2, 2, 2]],
      
              [[1, 1, 1],
               [2, 2, 2]],
      
              [[1, 1, 1],
               [2, 2, 2]]])
      
    2. 再次转置:

      >>> torch.stack((A.T, B.T), 1).transpose(1, 2)
      tensor([[[1, 2],
               [1, 2],
               [1, 2]],
      
              [[1, 2],
               [1, 2],
               [1, 2]],
      
              [[1, 2],
               [1, 2],
               [1, 2]],
      
              [[1, 2],
               [1, 2],
               [1, 2]],
      
              [[1, 2],
               [1, 2],
               [1, 2]]])
      
    3. 重塑为最终形式:

      >>> torch.stack((A.T, B.T), 1).transpose(1, 2).reshape(A.size(0), A.size(1)*2)
      tensor([[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
              [1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
              [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]])
      

    【讨论】:

      猜你喜欢
      • 2021-02-28
      • 2021-11-04
      • 2021-02-01
      • 1970-01-01
      • 2021-02-07
      • 2021-10-11
      • 2022-10-17
      • 2022-10-18
      • 2020-10-14
      相关资源
      最近更新 更多