Per the docs,
linalg.solve 用于计算“精确”解,x,
良好确定的,即满秩线性矩阵方程ax = b。
存在
线性的,最多只能有一个解。如果您找到的解决方案没有
总和为 1,然后添加额外的约束将不会产生任何解决方案。
但是,您可以使用
scipy.optimize.minimize
在约束平面上找到最小化数量的点
||Ax-b||^2:
def f(x):
y = np.dot(A, x) - b
return np.dot(y, y)
cons = ({'type': 'eq', 'fun': lambda x: x.sum() - 1})
res = optimize.minimize(f, [0, 0, 0], method='SLSQP', constraints=cons,
options={'disp': False})
例如,给定这个方程组
import numpy as np
import numpy.linalg as LA
import scipy.optimize as optimize
A = np.array([[1, 3, 4], [5, 6, 9], [1, 2, 3]])
b = np.array([1, 2, 1])
x = LA.solve(A, b)
解加起来不等于1:
print(x)
# [-0.5 -1.5 1.5]
但是你可以尝试最小化f:
def f(x):
y = np.dot(A, x) - b
return np.dot(y, y)
受限于cons:
cons = ({'type': 'eq', 'fun': lambda x: x.sum() - 1})
res = optimize.minimize(f, [0, 0, 0], method='SLSQP', constraints=cons,
options={'disp': False})
xbest = res['x']
# array([ 0.30000717, 1.89998823, -1.1999954 ])
xbest 和为 1:
print(xbest.sum())
1
A·xbest - b的区别是:
print(np.dot(A, xbest) - b)
# [ 0.19999026 0.10000663 -0.50000257]
差的平方和,(也可以计算为f(xbest))是:
print(res['fun'])
0.30000000014542572
在满足约束的同时,没有其他 x 值可以进一步最小化这个数量。