我可以使用 scipy.optimize.NonlinearConstraint 将参数发送到约束函数吗?
Can I send arguments to a constraint function using scipy.optimize.NonlinearConstraint?
我有一个非线性约束的有界优化问题,我正在尝试解决。非线性约束函数需要参数,这是我无法使其工作的地方。下面是我遵循的结构。如何将参数 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()。
trust-constr
与其他约束求解器有一些不同的方法。我没有看到将参数传递给约束的直接方法。当然,我们总是可以尝试把东西打包成class.
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
我有一个非线性约束的有界优化问题,我正在尝试解决。非线性约束函数需要参数,这是我无法使其工作的地方。下面是我遵循的结构。如何将参数 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()。
trust-constr
与其他约束求解器有一些不同的方法。我没有看到将参数传递给约束的直接方法。当然,我们总是可以尝试把东西打包成class.
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