簡體   English   中英

在 python 中反轉矩陣時遇到問題

[英]Trouble inverting a matrix in python

我在 python 中有一個矩陣,我正在嘗試反轉。 但是,將反轉矩陣乘以原始矩陣的結果不會產生單位矩陣。

M = np.matrix(cv)
invM = np.linalg.inv(M)
M@invM

顯示矩陣乘法結果的圖像

我不確定可能是什么問題,因為這是一個相當簡單的操作。 有沒有其他人有這個問題? 或者有誰知道如何解決這個問題? 謝謝!

很可能,您的矩陣是病態的,這意味着該矩陣接近於不可逆的。 您可以使用以下方法檢查矩陣的條件編號:

np.linalg.cond(M)

雙精度浮點數的相對精度約為 1e-16。 對於條件數 K,您會損失大約 K 倍的精度。 如果 K 大於 1e+15,則該矩陣實際上是不可逆的。

如果要為x求解A @ x = b ,通常使用x = np.linalg.solve(A, b)而不是x = np.linalg.inv(A) @ b更准確。

以下是一些具有不同條件數及其逆質量的矩陣:

import numpy as np
np.random.seed(1)
n = 100

def test_inv(a):
    print(f'Condition number: {np.linalg.cond(a):.3g}')
    max_err = np.abs(a @ np.linalg.inv(a) - np.eye(n)).max()
    print(f'a @ a_inv - eye: maximum error = {max_err:.3g}')    

# identity matrix
test_inv(np.eye(n))

# random numbers
randmat = np.random.uniform(-1, 1, size=(n, n))
test_inv(randmat)

# random numbers, but one row is almost a linear combination of
# two other rows.
badmat = randmat.copy()
badmat[1, :] = badmat[0, :] + badmat[2, :] - 1e-9
test_inv(badmat)

output:

Condition number: 1
a @ a_inv - eye: maximum error = 0
Condition number: 626
a @ a_inv - eye: maximum error = 2.84e-14
Condition number: 1.64e+10
a @ a_inv - eye: maximum error = 1.53e-06
m = np.matrix([[2,3],[4,5]])
n = m.I
i = m@n
print(i)

out:
[[1. 0.]
 [0. 1.]]

試試這個方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM