简体   繁体   English

Numpy:向量矩阵,求逆

[英]Numpy : matrix of vectors, inversion

I have a matrix A of dimensions N x N, each matrix element is a vector of size M. I want to inverse A matrix.我有一个维度为 N x N 的矩阵 A,每个矩阵元素都是一个大小为 M 的向量。我想对 A 矩阵求逆。 In other terms I want to compute A^-1 that is the inverted A matrix composed of NxN vectors of size M.换句话说,我想计算 A^-1,它是由大小为 M 的 NxN 个向量组成的倒 A 矩阵。

Here is code to implement what I want to do, I'm just computing M times inverse matrix to compute C = A^-1 x B and then I'm checking A x C = B. But each time I'm iterating over the M element of A, B elements to do a matrix inversion.这是实现我想做的代码,我只是计算 M 次逆矩阵来计算 C = A^-1 x B 然后我检查 A x C = B。但每次我迭代对A、B元素的M个元素做矩阵求逆。 I'm quite sure my code does what I need but not in a clever way...我很确定我的代码可以满足我的需要,但不是以一种聪明的方式...

a = np.array([[[3, 4, 8], [1,8,3]],
     [[2, 1, 2], [6, 5, 0]]])

b = np.array([[2, 0, 6],
     [5, 2, 5]])

c = []
# compute c = a^-1 x b
for i in range(a.shape[-1]):
    c.append(np.linalg.inv(a[:,:,i])@b[:,i])
c = np.asarray(c)

# check inversion compute a x c and checks a x c = b 
for i in range(a.shape[-1]):
    if not np.allclose(a[:,:,i]@c[i,:], b[:,i]):
        raise Exception('Inversion ko')
        break
print('inversion ok')

I need a mix of matrix operations and element wise operations.我需要矩阵运算和元素运算的混合。 But I do not like my implementations.但我不喜欢我的实现。 I'm quite a straightforward implementation with less code exists.我是一个非常简单的实现,存在的代码更少。 Let me know your suggestions.让我知道你的建议。

We can use np.linalg.inv on the 3D array a after pushing the last axis to the front.在将最后一个轴推到前面后,我们可以在 3D 阵列a上使用np.linalg.inv Then, we can leverage einsum for the final output for a vectorized way -然后,我们可以将einsum用于最终的 output 以采用矢量化方式 -

p = np.linalg.inv(a.transpose(2,0,1))
c = np.einsum('ijk,kli->ij',p,b)[...,None]

A simpler alternative to get the final output c would be with np.matmul/@-operator -获得最终 output c的更简单的替代方法是使用np.matmul/@-operator -

c = p@b.transpose(2,0,1)

Thus, the whole process could be converted to a one-liner -因此,整个过程可以转换为单行 -

c = np.linalg.inv(a.transpose(2,0,1))@b.transpose(2,0,1)

If you stacked your matrices along the first dimension, instead of the last, you can invert them all in one single np.linalg.pinv() call.如果您沿第一个维度而不是最后一个维度堆叠矩阵,则可以在一个np.linalg.pinv()调用中将它们全部反转。 Afterwards use np.einsum() to do all dot products in one go:然后使用np.einsum()在一个 go 中做所有点积:

a = a.transpose(2, 0, 1)
b = b.transpose()

np.einsum('fmn,fm->fn', np.linalg.inv(a), b)

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

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