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

标签 python numpy matrix equation-solving

我想使用 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/

相关文章:

Python:是否可以压缩我的类似方法列表

python - 为什么这个循环会随着时间的二次方缩放

python - 在Python中通过文本文件的索引创建矩阵

r - 根据两个坐标之间的最近距离对矩阵进行排序

python - scipy.optimize.minimize : ValueError: all the input arrays must have same number of dimensions

python - Dropbox API v2 使用 python 上传大文件

python - 迭代 pandas df rows 以根据条件计算新变量

arrays - 选择第一列值在列表中至少出现一次的行

python - 巴特沃斯滤波器 - 输出 x (-1)?

python - 动态构建通用 numpy 数组索引