我有两个具有相同形状的矩阵数组A和B:
A.形状= B.形状=(M,N,P)

我想沿着轴0计算Kronecker乘积,以便:

KP[ii,:,:] = A[ii,:,:]⊗B[ii,:,:]


有没有办法在numpy中执行此操作而不使用for循环?

谢谢!

例:

A = np.array([ [[1,0],
                [0,1]],
               [[1,0],
                [0,1]]
            ])

B = np.array([ [[1,0],
                [0,-1]],
               [[0,1],
                [1,0]]
            ])

KP = np.array( [
                [[1,0,0,0],
                 [0,-1,0,0],
                 [0,0,1,0],
                 [0,0,0,-1]],
                [[0,1,0,0],
                 [1,0,0,0],
                 [0,0,0,1],
                 [0,0,1,0]]
               ] )


相当于:

KP= np.zeros( (A.shape[0],
               A.shape[1]**2,
               A.shape[2]**2) )

for ii in range(A.shape[0]):

    KP[ii,:,:] = np.kron(A[ii,:,:],B[ii,:,:])

最佳答案

您可以使用einsum,只需稍加练习即可,它非常直观,也可以采用经典的重塑和广播路线

A = np.array([ [[1,0],
                [0,1]],
               [[1,0],
                [0,1]]
            ])

B = np.array([ [[1,0],
                [0,-1]],
               [[0,1],
                [1,0]]
            ])

i,j,k = A.shape
i,l,m = B.shape
np.einsum("ijk,ilm->ijlkm",A,B).reshape(i,j*l,k*m)

# array([[[ 1,  0,  0,  0],
#         [ 0, -1,  0,  0],
#         [ 0,  0,  1,  0],
#         [ 0,  0,  0, -1]],
#
#        [[ 0,  1,  0,  0],
#         [ 1,  0,  0,  0],
#         [ 0,  0,  0,  1],
#         [ 0,  0,  1,  0]]])


等效的非einsum表达式:

(A[:,:,None,:,None]*B[:,None,:,None,:]).reshape(i,j*l,k*m)

关于python-3.x - 矩阵阵列的Kronecker积,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57259557/

10-12 21:18