我可以使用scipy.optimize.NonlinearConstraint将参数发送到约束函数吗?

2024-09-28 17:24:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带非线性约束的有界优化问题,我正试图解决这个问题。非线性约束函数需要参数,这就是我无法使它工作的地方。下面是我遵循的结构。如何将参数arg3, arg4, arg5发送到约束函数cons

from scipy.optimize import (BFGS, SR1, Bounds, NonlinearConstraint, minimize)

def objfcn(x, arg1, arg2):
    ...
    return out1

def cons(x, arg3, arg4, arg5):
    ...
    return out2


bounds = Bounds([-d, -d, -d, -d], [d, d, d, d])
nonlinear_constraint = NonlinearConstraint(cons, 0.0, 0.0, jac='2-point', hess=BFGS())
res = minimize(objfcn,
                x0,
                args=(arg1, arg2),
                method='trust-constr',
                jac="2-point",
                hess=SR1(),
                constraints=[nonlinear_constraint]
                options={'verbose': 1},
                bounds=bounds)

编辑:当前不太好的解决方案是通过全局变量将参数传递给约束函数cons()


Tags: 函数参数defarg3arg1boundsbfgsminimize
1条回答
网友
1楼 · 发布于 2024-09-28 17:24:41

trust-constr与其他约束解算器有一点不同的方法。我没有看到将参数传递给约束的直接方法。当然,我们可以试着在课堂上打包东西

from scipy.optimize import (BFGS, SR1, Bounds, NonlinearConstraint, minimize)

class problem:
  arg1 = 1
  arg2 = 2
  arg3 = 3

  def f(self,x):
    return -x[0]*self.arg1-x[1]*self.arg2

  def g(self,x):
    return x[0]-self.arg3*x[1]

p = problem()


bounds = Bounds([0,0], [2,3])
nonlinear_constraint = NonlinearConstraint(p.g, 0.0, 0.0, jac='2-point', hess=BFGS())
res = minimize(p.f,
                x0=[0,0],
                method='trust-constr',
                jac="2-point",
                hess=SR1(),
                constraints=[nonlinear_constraint],
                options={'verbose': 1},
                bounds=bounds)
res 

相关问题 更多 >