Python:为什么我在尝试计算 2x2 矩阵(Hessian)的逆矩阵时收到错误消息?

Python: Why do I get error message when I try to calculate the inverse of my 2x2-matrix (Hessian)?

我的 Hessian(2x2 矩阵)如下所示:

Hessian1


[[array([[ -400451.22705586, -1472873.29657509, -1353698.36178183],
         [-1472873.29657509, -5425857.74291764, -4978945.85451078],
         [-1353698.36178183, -4978945.85451078, -4591731.95233015]]),
  array([[-2.51920250e-07],
         [-9.37914803e-07],
         [-4.97061494e-07]])],
 [array([[-2.51920250e-07, -9.37914803e-07, -4.97061494e-07]]),
  array([[-1600445.78266049]])]]

也就是说,它是一个 2x2 矩阵,第一个元素是 3x3 矩阵 (1,1),第二个元素是 3x1 矩阵 (1,2),依此类推。

现在我想取这个矩阵的逆。

np.linalg.inv(Hessian1)

但我收到以下错误消息:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-d820d7b5b57d> in <module>
----> 1 np.linalg.inv(Hessian1)

<__array_function__ internals> in inv(*args, **kwargs)

~\anaconda3\lib\site-packages\numpy\linalg\linalg.py in inv(a)
    545     signature = 'D->D' if isComplexType(t) else 'd->d'
    546     extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
--> 547     ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj)
    548     return wrap(ainv.astype(result_t, copy=False))
    549 

TypeError: No loop matching the specified signature and casting was found for ufunc inv

我不理解消息,因为我没有循环。有人可以帮我求逆吗?

这里是np.linalg.inv

文档的第一行
Docstring:
Compute the (multiplicative) inverse of a matrix.

Given a square matrix `a`, return the matrix `ainv` satisfying
``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``

平方表示矩阵的每个元素都应该是同一类型(float8、16、32 等)。 您没有 2 x 2 矩阵,但实际上是 4 x 4 矩阵。这是矩阵图:

x  x   x   y
x  x   x   y
x  x   x   y
r  r   r   s

x是存储在Hessian1中的3x3矩阵,y 3x1,r 1x3和s 1x1。

这是将 hessian1 映射到您可以操作的矩阵的方法:

H = np.vstack([
np.hstack([Hessian1[0][0],Hessian1[0][1]]),
np.hstack([Hessian1[0][1].T,Hessian1[1][1]])
])

您可以申请 np.linalg.inv(H) 并找到:

array([[-2.31020535e-03,  4.28778776e-04,  2.16139552e-04,
         4.52342092e-17],
       [ 4.28778776e-04, -1.16557869e-04, -2.21714591e-08,
         8.21218296e-19],
       [ 2.16139552e-04, -2.21714591e-08, -6.39143074e-05,
        -1.41584265e-17],
       [ 4.52342092e-17,  8.21218296e-19, -1.41584265e-17,
        -6.24825915e-07]])