Mat2cell Matlab在张量流或pytorch中等效

时间:2019-06-14 14:31:42

标签: tensorflow matrix pytorch

我有一个方矩阵,喜欢将其分解为一些较小的矩阵。例如,假设我们有一个[4,4]形状的矩阵,并想将其转换为大小为[2,2]的4个较小的矩阵。

输入:

[9, 9, 9, 9,
 8, 8, 8, 8,
 7, 7, 7, 7,
 6, 6, 6, 6] 

输出:

[[9, 9  | [9, 9,
 8, 8]  | 8, 8],
 ---------------
 [7, 7  | [7, 7,
 6, 6]  | 6, 6]] 

2 个答案:

答案 0 :(得分:0)

为此,您可以重复调用torch.split

>>> x
tensor([[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12],
        [13, 14, 15, 16]])
>>> [z for y in x.split(2) for z in y.split(2, dim=1)]
[tensor([[1, 2],
        [5, 6]]), tensor([[3, 4],
        [7, 8]]), tensor([[ 9, 10],
        [13, 14]]), tensor([[11, 12],
        [15, 16]])]

答案 1 :(得分:0)

给出具有4*41*16形状的张量,最简单的方法是通过视图函数或整形:

a = torch.tensor([9, 9, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6])
# a = a.view(4,4)
a = a.view(2, 2, 2, 2)

# output:
tensor([[[[9, 9],
          [9, 9]],

         [[8, 8],
          [8, 8]]],


        [[[7, 7],
          [7, 7]],

         [[6, 6],
          [6, 6]]]])