numpy Pytorch:正确地将列重新整形为矩阵

zd287kbt  于 2023-03-30  发布在  其他
关注(0)|答案(1)|浏览(164)

我在正确地重塑从稀疏矩阵和输入相乘获得的这些列时遇到了麻烦。例如,假设我有以下形状的稀疏矩阵:torch.Size([2,972])和形状为:torch.Size([108, 2]),通过转换输入向量并进行点积,I获得大小为torch.Size([2, 9, 2]))的TensorA,定义如下:

tensor([[[ 34480,  49811],
         [ 62672,  72119],
         [ 49617, 129834],
         [ 58862,  69061],
         [209598, 165029],
         [157133, 144929],
         [ 86957,  91814],
         [205047, 228574],
         [230294, 144340]],

        [[ 31880,  73623],
         [ 73641, 150267],
         [ 91390, 112184],
         [ 56916,  72953],
         [227125, 192221],
         [145567, 110968],
         [ 83470,  77461],
         [203651, 246334],
         [258275, 117184]]]),

tensor.Size([2,9,2])

现在我想做的是将A重新塑造为大小为(2,2,3,3)的Tensor如下:

tensor([[[[ 34480,  62672,  49617],
          [ 58862, 209598, 157133],
          [ 86957, 205047, 230294]],

         [[ 31880,  73641,  91390],
          [ 56916, 227125, 145567],
          [ 83470, 203651, 258275]]]])
tensor([[[[ 49811,  72119, 129834],
          [ 69061, 165029, 144929],
          [ 91814, 228574, 144340]],

         [[ 73623, 150267, 112184],
          [ 72953, 192221, 110968],
          [ 77461, 246334, 117184]]]])

但是做A.reshape(2,2,3,3),我得到了这个:

tensor([[[[ 34480,  49811,  62672],
          [ 72119,  49617, 129834],
          [ 58862,  69061, 209598]],

         [[165029, 157133, 144929],
          [ 86957,  91814, 205047],
          [228574, 230294, 144340]]],

        [[[ 31880,  73623,  73641],
          [150267,  91390, 112184],
          [ 56916,  72953, 227125]],

         [[192221, 145567, 110968],
          [ 83470,  77461, 203651],
          [246334, 258275, 117184]]]]))

如何正确地重塑A?

bfhwhh0e

bfhwhh0e1#

特别感谢@Chrysophylaxs解决了我的问题,我会在这里转发他的评论:
你可以使用permute来代替两次转置:A.permute(2, 0, 1).reshape(2, 2, 3, 3).
加油,继续编码!

相关问题