NumPy数组上的反向堆叠操作

时间:2019-04-02 20:49:40

标签: python arrays numpy vectorization reshape

我有一行代码可以有效地将一个numpy数组的形状从400x8x8数组重塑为160x160数组,我需要颠倒这一过程,但无法弄清这一行的相反方向。

我已经可以执行此过程,但是它效率很低,并且需要嵌套循环,出于性能考虑,我希望避免嵌套循环。

这是我目前必须逆转此过程的代码(160x160> 400x8x8):

       previousRow = 0
    for rowBlock in range(noBlocksOn1Axis):
        previousRow = rowBlock * blockSize  
        previousColumn = 0
        for columnBlock in range(noBlocksOn1Axis):
            previousColumn = columnBlock * blockSize
            block = 
            arrayY[previousRow:previousRow+blockSize, 
            previousColumn:previousColumn + blockSize]
            blocksList.append(block) 

这是重新设计400x8x8> 160x160的代码行:

    xy = np.zeros((160,160), dtype = np.uint8)

    xy = np.vstack(np.hstack(overDone[20*i:20+20*i]) for i in 
    range(overDone.shape[0]//20))

那么关于如何反向执行这一行代码的任何想法?

谢谢:D

2 个答案:

答案 0 :(得分:2)

重塑,交换轴(或转置轴)并重塑以使overDone返回-

xy.reshape(20,8,20,8).swapaxes(1,2).reshape(400,8,8)

有关intuition behind nd-to-nd array transformation的更多信息。

将其通用以处理通用形状-

m,n = xy.shape
M,N = 20,20 # block size used to get xy
overDone_ = xy.reshape(M,m//M,N,n//N).swapaxes(1,2).reshape(-1,m//M,n//N)

样品运行-

# Original input
In [21]: overDone = np.random.rand(400,8,8)

# Perform forward step to get xy
In [22]: xy = np.vstack(np.hstack(overDone[20*i:20+20*i]) for i in range(overDone.shape[0]//20))

# Use proposed approach to get back overDone
In [23]: out = xy.reshape(20,8,20,8).swapaxes(1,2).reshape(400,8,8)

# Verify output to be same as overDone
In [42]: np.array_equal(out,overDone)
Out[42]: True

奖金:

我们可以使用相同的向量化reshape+permute-axes步骤为前进过程创建xy-

xy = overDone.reshape(20,20,8,8).swapaxes(1,2).reshape(160,160)

答案 1 :(得分:0)

numpy.reshape怎么了?

<UpdateWaypointDialog
  open={updateWaypointDialogOpen}
  onClose={()=> this.handleUpdateWaypointDialogClose(waypoint)}
   updateWaypoint={this.updateWaypoint}
  index={i}
  waypoint={waypoint} />