通过组合较小的张量创建张量

creating tensor by composition of smaller tensors

我想以这种方式创建一个由四个较小的 2x2 张量组成的 4x4 张量:

我要创建的张量:

in_t = torch.tensor([[14,  7,  6,  2],
                     [ 4,  8, 11,  1],
                     [ 3,  5,  9, 10],
                     [12, 15, 16, 13]])

我想创建由这四个较小的张量组成的张量:

a = torch.tensor([[14, 7], [ 4,  8]])
b = torch.tensor([[6,  2], [11,  1]])
c = torch.tensor([[3,  5], [12, 15]])
d = torch.tensor([[9, 10], [16, 13]])

我试过这样使用torch.cat

mm_ab = torch.cat((a,b,c,d), dim=0)

但我最终得到了一个 8x2 张量。

您可以通过 torch.transpose and torch.reshape 的组合来控制张量的布局并获得所需的结果。您可以执行 outer 转置,然后执行 inner 转置:

>>> stack = torch.stack((a,b,c,d))
tensor([[[14,  7],
         [ 4,  8]],

        [[ 6,  2],
         [11,  1]],

        [[ 3,  5],
         [12, 15]],

        [[ 9, 10],
         [16, 13]]])

Reshape-tranpose-reshape-transpose-reshape:

>>> stack.reshape(4,2,-1).transpose(0,1).reshape(-1,2,4).transpose(0,1).reshape(-1,4)
tensor([[14,  7,  6,  2],
        [ 4,  8, 11,  1],
        [ 3,  5,  9, 10],
        [12, 15, 16, 13]])

本质上,重塑允许您以不同的方式对张量进行分组和查看,而转置操作将改变其布局(它不会保持连续),这意味着您可以获得所需的输出。

如果您按照下面的方式连接所有张量,您将得到准确的输出:

tensor a tensor b
tensor c tensor d

您确实是从一个简单易行的方法开始的,这是您尝试的完成:

p1 = torch.concat((a,b),axis=1)
p2 = torch.concat((c,d),axis=1)
p3 = torch.concat((p1,p2),axis=0)
print(p3)

#output
tensor([[14,  7,  6,  2],
        [ 4,  8, 11,  1],
        [ 3,  5,  9, 10],
        [12, 15, 16, 13]])