仅使用Numpy和Python的约束最小二乘法[已关闭]

eoxn13cs  于 2023-08-05  发布在  Python
关注(0)|答案(1)|浏览(102)

**已关闭。**此问题需要debugging details。它目前不接受回答。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答这个问题。
8天前关闭。
Improve this question
如何仅使用numpy进行约束最小二乘法。是否有任何方法将约束合并到numpy.linalg.lstsq()中,或者是否有任何numpy +Python解决方案来执行约束最小二乘法?我知道我可以用cvxpyscipy.optimize轻松地做到这一点,但这种优化将是numba JIT函数的一部分,而numba不支持这两个。
编辑:这里有一个我想解决的问题的虚拟例子

arr_true = np.vstack([np.random.normal(0.3, 2, size=20),
                      np.random.normal(1.4, 2, size=20),
                      np.random.normal(4.2, 2, size=20)]).transpose()
x_true = np.array([0.3, 0.35, 0.35])
y = arr_true @ x_true

def problem():
    noisy_arr = np.vstack([np.random.normal(0.3, 2, size=20),
                        np.random.normal(1.4, 2, size=20),
                        np.random.normal(4.2, 2, size=20)]).transpose()

    x = cvxpy.Variable(3)
    objective = cvxpy.Minimize(cvxpy.sum_squares(noisy_arr @ x - y))
    constraints = [0 <= x, x <= 1, cvxpy.sum(x) == 1]
    prob = cvxpy.Problem(objective, constraints)
    result = prob.solve()
    output = prob.value
    args = x.value

    return output, args

字符串
本质上,我的问题是最小化$Ax-y$,满足$x_1+x_2+x_3 = 1$和$\forall x_i,0 \leq x_i \leq 1$。

qlfbtfca

qlfbtfca1#

它是线性的吗?基于您的numpy.linalg.lstsq建议,我暂时假设是这样。此外,我假设(首先解决简单的情况)您谈论的是等式约束。然后你可以很容易地解决它自己通过使用拉格朗日乘子,解决方案可以找到解决一个线性方程组。
如果问题是在约束B * x = b上最小化A * x - y,则求解
x1c 0d1x的数据
例如:

from numpy import array, zeros
from numpy.linalg import solve

A = array([[1, 2], [3, 4], [5, 6], [7, 8]])
y = array([3.2, 6.8, 11.1, 15.2])

B = array([[1, -1]])
b = array([0.1])

S = zeros((3, 3))
r = zeros(3)

S[:2, :2] = A.T @ A
S[2:, :2] = B
S[:2, 2:] = B.T
r[:2] = A.T @ y
r[2] = b

x = solve(S, r)[:2]
print(x)

字符串
Disclamer:可能包括bug,但简短的测试给了我x

[1.06262376 0.96262376]


这似乎是合理的,我的约束x1- x2 = 0.1也得到了满足。

相关问题