gpt4 book ai didi

python - 使用带约束的 linalg 求解系统

转载 作者:太空狗 更新时间:2023-10-30 02:03:31 24 4
gpt4 key购买 nike

我想使用 linalg 以矩阵形式求解某个系统,但所得解的总和应为 1。例如,假设有 3 个未知数 x、y、z。求解系统后,它们的值总和应为 1,例如 .3、.5、.2。谁能告诉我该怎么做?

目前,我正在使用类似result = linalg.solve(A, B) 的方法,其中AB 是矩阵。但这不会返回 [0, 1] 范围内的解决方案。

最佳答案

Per the docs ,

linalg.solve is used to compute the "exact" solution, x, of the well-determined, i.e., full rank, linear matrix equation 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 = ({'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 值更能最小化该数量。

关于python - 使用带约束的 linalg 求解系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31098228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com