scipy dist_squares的方程式约束

发布于 2025-02-07 10:20:29 字数 472 浏览 0 评论 0原文

我正在尝试通过更改x,y,z来最大程度地减少损失函数。我的问题是非线性,因此为什么我选择scipy dist_squares。一般结构是:

from scipy.optimize import least_squares
def loss_func(x, *arguments):
 # plug x's and args into an arbitrary equation and return loss
 return loss # loss here is an array

# x_arr contains x,y,z
res = least_squares(loss_func, x_arr, args=arguments)

我试图限制x,y,z by:xy =某些值,zy =一些值。我该怎么做? Scipy最少_squares文档仅提供界限。我了解我可以创建界限,例如0< x< 5。但是,我的约束是一个方程,而不是常数绑定。先感谢您!

I'm trying to use least square to minimize a loss function by changing x,y,z. My problem is nonlinear hence why i chose scipy least_squares. The general structure is:

from scipy.optimize import least_squares
def loss_func(x, *arguments):
 # plug x's and args into an arbitrary equation and return loss
 return loss # loss here is an array

# x_arr contains x,y,z
res = least_squares(loss_func, x_arr, args=arguments)

I am trying to constraint x,y,z by: x-y = some value, z-y = some value. How do I go about doing so? The scipy least_squares documentation only provided bounds. I understand I can create bounds like 0<x<5. However, my constraints is an equation and not a constant bound. Thank you in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

耀眼的星火 2025-02-14 10:20:29

如果有人偶然发现这个问题,我已经想出了如何克服这个问题。由于最小二乘没有约束,因此最好仅将线性编程与scipy.optimize.minimize一起使用。由于lose_func返回一系列残差,因此我们可以使用L1 Norm(因为我们希望最大程度地减少此残差数组的绝对差异)。

from scipy.optimize import minimize
import numpy as np

def loss_func(x, *arguments):
 # plug x's and args into an arbitrary equation and return loss (loss is an array)
 return np.linalg.norm(loss, 1)

界限可以添加到scipy.optimize.minimize。

If anyone ever stumble on this question, I've figured out how to overcome this issue. Since least_squares does not have constraints, it is best to just use linear programming with scipy.optimize.minimize. Since the loss_func returns an array of residuals, we can use L1 norm (as we want to minimize the absolute difference of this array of residuals).

from scipy.optimize import minimize
import numpy as np

def loss_func(x, *arguments):
 # plug x's and args into an arbitrary equation and return loss (loss is an array)
 return np.linalg.norm(loss, 1)

The bounds can be added to scipy.optimize.minimize fairly easily:)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文