在多维空间中将多个子矩阵重塑/合并为一个矩阵 [英] Reshaping/Combining several sub-matrices to one matrix in multi-dimensional space

查看:92
本文介绍了在多维空间中将多个子矩阵重塑/合并为一个矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个5D二进制数组'a',其大小为(2、2、4、2、2).该结构如下所示,例如:

I have a 5D binary array 'a' of size (2, 2, 4, 2, 2). The structure looks like this, for example:

a[0,0]:
[[[ 0.  1.]
  [ 0.  0.]]

 [[ 0.  0.]
  [ 0.  1.]]

 [[ 0.  0.]
  [ 0.  1.]]

 [[ 0.  0.]
  [ 1.  0.]]]

我想要做的是制作一个(2,2,4,4)矩阵,该矩阵在最后两个轴上以正方形结构组合2x2矩阵.

What I want to do is to make a (2,2,4,4) matrix that combines the 2x2 matrices in the last two axis, but in a squared structure.

结果应如下所示:

result[0,0]:
[[0. 1. 0. 0.]
 [0. 0. 0. 1.]
 [0. 0. 0. 0.]
 [0. 1. 1. 0.]]

我希望这足够清楚.如果将原始矩阵的括号放在结果中,则看起来像这样:

I hope this is clear enough. If I put the brackets of original matrices in results, it looks like this:

result[0,0]:
[[[0. 1. [0. 0.]
 [0. 0.] 0. 1.]]
 [[0. 0. [0. 0.]
 [0. 1.] 1. 0.]]]

推荐答案

似乎您正在将第三个轴从(4)分解为(2,2),并将拆分轴的前一半引入到倒数第二个轴位置.因此,有两种方法可以使用 np.reshape ,就像这样-

It seems you are breaking the third axis from (4) into (2,2) and bringing in the first half of the split axes to the second last axes position. So, there are two ways to achieve such an output using np.reshape and np.transpose, like so -

out = a.reshape(2,2,2,2,2,2).transpose(0,1,3,4,2,5).reshape(2,2,4,4)

out = a.reshape(2,2,2,-1,2).transpose(0,1,3,2,4).reshape(2,2,4,4)

样品运行-

In [69]: a[0][0]
Out[69]: 
array([[[49, 91],
        [10, 32]],

       [[71, 27],
        [50, 64]],

       [[ 9, 41],
        [73, 52]],

       [[54, 85],
        [53, 36]]])

In [70]: out1 = a.reshape(2,2,2,2,2,2).transpose(0,1,3,4,2,5).reshape(2,2,4,4)

In [71]: out2 = a.reshape(2,2,2,-1,2).transpose(0,1,3,2,4).reshape(2,2,4,4)

In [72]: out1[0][0]
Out[72]: 
array([[49, 91,  9, 41],
       [10, 32, 73, 52],
       [71, 27, 54, 85],
       [50, 64, 53, 36]])

In [73]: out2[0][0]
Out[73]: 
array([[49, 91,  9, 41],
       [10, 32, 73, 52],
       [71, 27, 54, 85],
       [50, 64, 53, 36]])

这篇关于在多维空间中将多个子矩阵重塑/合并为一个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆