简体   繁体   English

在2-D数组之间重塑4-D ndarray

[英]Reshapeing 4-D ndarray to and from 2-D array

I have a 4-D array which I need to convert to 2-D, do some operations, and then convert back to 4-D. 我有一个4-D数组,需要将其转换为2-D,执行一些操作,然后再转换回4-D。 It is important that the order of the elements are preserved for the operation. 为操作保留元素的顺序很重要。 From this post I got out how to do this reshape operation using np.swapaxes(1, 2) . 这篇文章中,我了解了如何使用np.swapaxes(1, 2)进行np.swapaxes(1, 2)操作。

But now I am confused how to re-shape it back to the original 4D matrix that started of with. 但是现在我很困惑如何将其重塑为最初的4D矩阵。

How do I do this with standard numpy methods. 我该如何使用标准的numpy方法做到这一点。

4 to 2 and back: 4比2并返回:

In [348]: arr4 = np.arange(2*3*4*5).reshape(2,3,4,5)
In [349]: arr2 = arr4.transpose(0,2,1,3).reshape(8,15)
In [350]: arr2
Out[350]: 
array([[  0,   1,   2,   3,   4,  20,  21,  22,  23,  24,  40,  41,  42,
         43,  44],
       [  5,   6,   7,   8,   9,  25,  26,  27,  28,  29,  45,  46,  47,
         48,  49],
       [ 10,  11,  12,  13,  14,  30,  31,  32,  33,  34,  50,  51,  52,
         53,  54],
       [ 15,  16,  17,  18,  19,  35,  36,  37,  38,  39,  55,  56,  57,
         58,  59],
       [ 60,  61,  62,  63,  64,  80,  81,  82,  83,  84, 100, 101, 102,
        103, 104],
       [ 65,  66,  67,  68,  69,  85,  86,  87,  88,  89, 105, 106, 107,
        108, 109],
       [ 70,  71,  72,  73,  74,  90,  91,  92,  93,  94, 110, 111, 112,
        113, 114],
       [ 75,  76,  77,  78,  79,  95,  96,  97,  98,  99, 115, 116, 117,
        118, 119]])

In [351]: arrN = arr2.reshape(2,4,3,5).transpose(0,2,1,3)
In [352]: np.allclose(arr4,arrN)
Out[352]: True

I'm using transpose with parameter, but swapaxes would work just as well. 我正在使用带有参数的transpose ,但是swapaxes也可以工作。 For testing it's convenient to keep dimensions distinct. 为了进行测试,保持尺寸不同很方便。 That way most mistakes will result in errors or obvious mismatches. 这样,大多数错误将导致错误或明显的不匹配。 The original 4x5 inner blocks are still evident in the 2d array. 原始的4x5内部块在2d阵列中仍然很明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM