[英]How to give additional input to objective function of scipy.optimize.minimize other than independent variables
I am using scipy library for an optimization task. 我正在使用scipy库执行优化任务。 I have a function which has to be minimized.
我有一个必须最小化的功能。 My code and function looks like
我的代码和功能看起来像
import numpy as np
from scipy.optimize import minimize
from scipy.optimize import Bounds
bounds = Bounds([2,10],[5,20])
x0 = np.array([2.5,15])
def objective(x):
x0 = x[0]
x1 = x[1]
return a*x0 + b*x0*x1 - c*x1*x1
res = minimize(objective, x0, method='trust-constr',options={'verbose': 1}, bounds=bounds)
My a,b and c values change over time and are not constant. 我的a,b和c值随时间变化并且不是恒定的。 The function should not be optimized for a,b,c values but should be optimized for a given a,b,c values which can change over time.
该函数不应针对a,b,c值进行优化,而应针对可随时间变化的给定a,b,c值进行优化。 How do I give these values as an input to the objective function?
如何将这些值作为目标函数的输入?
The documentation for scipy.optimize.minimize
mentions the args
parameter: scipy.optimize.minimize
的文档中提到了args
参数:
args : tuple, optional
args:元组,可选
Extra arguments passed to the objective function and its derivatives (fun, jac and hess functions).
额外的参数传递给目标函数及其派生函数(fun,jac和hess函数)。
You can use it as follows: 您可以按以下方式使用它:
import numpy as np
from scipy.optimize import minimize
from scipy.optimize import Bounds
bounds = Bounds([2,10],[5,20])
x0 = np.array([2.5,15])
def objective(x, *args):
a, b, c = args # or just use args[0], args[1], args[2]
x0 = x[0]
x1 = x[1]
return a*x0 + b*x0*x1 - c*x1*x1
# Pass in a tuple with the wanted arguments a, b, c
res = minimize(objective, x0, args=(1,-2,3), method='trust-constr',options={'verbose': 1}, bounds=bounds)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.