除了自变量之外,如何为 scipy.optimize.minimize 的 objective 函数提供额外的输入
How to give additional input to objective function of scipy.optimize.minimize other than independent variables
我正在使用 scipy 库进行优化任务。
我有一个必须最小化的功能。我的代码和函数看起来像
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)
我的 a、b 和 c 值随时间变化,不是恒定的。该函数不应针对 a、b、c 值进行优化,而应针对可能随时间变化的给定 a、b、c 值进行优化。如何将这些值作为 objective 函数的输入?
scipy.optimize.minimize
的documentation提到了args
参数:
args : tuple, optional
Extra arguments passed to the objective function and its derivatives (fun, jac and hess functions).
您可以按如下方式使用:
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)
我正在使用 scipy 库进行优化任务。 我有一个必须最小化的功能。我的代码和函数看起来像
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)
我的 a、b 和 c 值随时间变化,不是恒定的。该函数不应针对 a、b、c 值进行优化,而应针对可能随时间变化的给定 a、b、c 值进行优化。如何将这些值作为 objective 函数的输入?
scipy.optimize.minimize
的documentation提到了args
参数:
args : tuple, optional
Extra arguments passed to the objective function and its derivatives (fun, jac and hess functions).
您可以按如下方式使用:
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)