nik*_*las 5 python numpy matrix-inverse singular
下面的矩阵是奇异的,AFAIK 试图反转它应该导致
numpy.linalg.linalg.LinAlgError: Singular matrix
Run Code Online (Sandbox Code Playgroud)
但相反,我确实得到了一些输出矩阵。请注意,输出矩阵是一个无意义的结果,因为它有一行 0(这是不可能的,因为矩阵的逆本身应该是可逆的)!
我是否在这里遗漏了与浮点精度或伪逆计算而不是真逆计算相关的内容?
$ np.__version__
'1.13.1'
$ np.linalg.inv(np.array([[2,7,7],[7,7,7],[8,7,7]]))
array([[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00],
[ 3.43131400e+15, -2.05878840e+16, 1.71565700e+16],
[ -3.43131400e+15, 2.05878840e+16, -1.71565700e+16]])```
Run Code Online (Sandbox Code Playgroud)
Behind the scenes, NumPy and SciPy (and many other software) fall back to LAPACK implementations (or C translations) of linear equation solvers (in this case GESV).
Since GESV first performs a LU decomposition and then checks the diagonal of U matrix for exact zeros, it is very difficult to hit perfect zeros in the decompositions. That's why you don't get a singular matrix error.
Apart from that you should never ever invert a matrix if you are multiplying with other matrices but instead solve for AX=B.
In SciPy since version 0.19, scipy.linalg.solve uses the "expert" driver GESVX of GESV which also reports back condition number and a warning is emitted. This is similar to matlab behavior in case the singularity is missed.
In [7]: sp.linalg.solve(np.array([[2,7,7],[7,7,7],[8,7,7]]), np.eye(3))
...\lib\site-packages\scipy\linalg\basic.py:223: RuntimeWarning: scipy.linalg.solve
Ill-conditioned matrix detected. Result is not guaranteed to be accurate.
Reciprocal condition number: 1.1564823173178713e-18
' condition number: {}'.format(rcond), RuntimeWarning)
Out[7]:
array([[ 0.00000000e+00, -1.00000000e+00, 1.50000000e+00],
[ 3.43131400e+15, -2.05878840e+16, 1.71565700e+16],
[ -3.43131400e+15, 2.05878840e+16, -1.71565700e+16]])
Run Code Online (Sandbox Code Playgroud)
numpy 团队的一则注释:
该领域事实上的约定是矩阵求逆中的错误大多被默默地忽略——假设用户知道这是否需要检查(这意味着需要更受控制的近似求逆方法)使用——正则化取决于问题)。
https://github.com/numpy/numpy/issues/2074
然而似乎在 1.13.0 上出现错误