在多维numpy数组中迭代向量

ema*_*rti 2 python numpy

我有一个3xNxM numpy数组a,我想迭代最后两个轴:a [:,x,y].优雅的方法是:

import numpy as np
a = np.arange(60).reshape((3,4,5))
M = np. array([[1,0,0],
               [0,0,0],
               [0,0,-1]])

for x in arange(a.shape[1]):
    for y in arange(a.shape[2]):
        a[:,x,y] = M.dot(a[:,x,y])
Run Code Online (Sandbox Code Playgroud)

这可以用nditer完成吗?这样做的目的是对每个条目执行矩阵乘法,例如[:,x,y] = M [:,:,x,y] .dot(a [:,x,y]).另一种MATLAB风格的方法是将a(3,N*M)和M重塑为(3,3*N*M)并采用点积,但这往往会占用大量内存.

Jai*_*ime 5

虽然对形状进行愚弄可能会使你想要完成的事情变得更加清晰,但是在不考虑太多问题的情况下处理这类问题的最简单方法是np.einsum:

In [5]: np.einsum('ij, jkl', M, a)
Out[5]: 
array([[[  0,   1,   2,   3,   4],
        [  5,   6,   7,   8,   9],
        [ 10,  11,  12,  13,  14],
        [ 15,  16,  17,  18,  19]],

       [[  0,   0,   0,   0,   0],
        [  0,   0,   0,   0,   0],
        [  0,   0,   0,   0,   0],
        [  0,   0,   0,   0,   0]],

       [[-40, -41, -42, -43, -44],
        [-45, -46, -47, -48, -49],
        [-50, -51, -52, -53, -54],
        [-55, -56, -57, -58, -59]]])
Run Code Online (Sandbox Code Playgroud)

此外,它通常还带有性能奖励:

In [17]: a = np.random.randint(256, size=(3, 1000, 2000))

In [18]: %timeit np.dot(M, a.swapaxes(0,1))
10 loops, best of 3: 116 ms per loop

In [19]: %timeit np.einsum('ij, jkl', M, a)
10 loops, best of 3: 60.7 ms per loop
Run Code Online (Sandbox Code Playgroud)

编辑 einsum是非常强大的伏都教.你也可以在下面的评论中做OP所要求的内容,如下所示:

>>> a = np.arange(60).reshape((3,4,5))
>>> M = np.array([[1,0,0], [0,0,0], [0,0,-1]])
>>> M = M.reshape((3,3,1,1)).repeat(4,axis=2).repeat(5,axis=3)
>>> np.einsum('ijkl,jkl->ikl', M, b)
array([[[  0,   1,   2,   3,   4],
        [  5,   6,   7,   8,   9],
        [ 10,  11,  12,  13,  14],
        [ 15,  16,  17,  18,  19]],

       [[  0,   0,   0,   0,   0],
        [  0,   0,   0,   0,   0],
        [  0,   0,   0,   0,   0],
        [  0,   0,   0,   0,   0]],

       [[-40, -41, -42, -43, -44],
        [-45, -46, -47, -48, -49],
        [-50, -51, -52, -53, -54],
        [-55, -56, -57, -58, -59]]])
Run Code Online (Sandbox Code Playgroud)