我正在使用 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 值进行优化。如何将这些值作为目标函数的输入?
最佳答案
documentation对于 scipy.optimize.minimize 提到了 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)
关于python - 除了自变量之外,如何为 scipy.optimize.minimize 的目标函数提供额外的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56630360/