簡體   English   中英

如何使用Python(NumPy,SciPy等)求解AX = B方程,其中A,X,B是矩陣,並且X的所有元素都必須為非負數

[英]How to solve AX = B equation with Python (NumPy, SciPy etc.), where A, X, B are matrices and all elements of X must be non-negative

我需要使用Python求解方程AX = B,其中A,X,B是矩陣,並且X的所有值都必須為非負數。

我發現的最佳解決方案是

X = np.linalg.lstsq(A, B, rcond=None)

但結果X包含負值。 是否可以獲得沒有負值的解決方案? 提前致謝!

通常,這在數學上是不可能的。 考慮到AB的基本要求是可逆的, X是唯一矩陣。 如果您不喜歡X具有的元素,則不能簡單地尋求另一種解決方案:沒有。 您必須更改AB才能獲得不同的結果。

您可以使用cvxpy解決它:

import cvxpy

def solve(A, B):
    """
    Minimizes |AX - B|**2, assuming A and B are 
    square matrices for simplicity. If this optimized 
    error is zero, this corresponds to solving AX = B.
    """
    n = A.shape[0]
    X = cvxpy.Variable((n,n))
    # Set objective
    obj_fun = cvxpy.sum_squares(A*X - B)
    objective = cvxpy.Minimize(obj_fun)
    # Set constraints
    constraints = [X >= 0]
    prob = cvxpy.Problem(objective, constraints)
    result = prob.solve(solver = "ECOS")
    return X.value

編輯:我相信Prune的答案是正確的。 您可以通過檢查results來檢查數值求解器中的誤差是否為非零。

暫無
暫無

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

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