python - 除了自变量之外,如何为 scipy.optimize.minimize 的目标函数提供额外的输入

标签 python python-3.x scipy scipy-optimize scipy-optimize-minimize

我正在使用 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/

相关文章:

python - Pandas 数据帧值拒绝被评估为带有 `.apply(eval)` 的 float 。为什么?

python - 导入错误 : cannot import name __check_build while importing TfidfVectorizer from sklearn

c++ - 向 Python 公开 C++ API

python - 返回列中的第一个数值

python - 如何在 tensorflow 中正确地将一个数组附加到另​​一个数组?

python - 如何使用 Beautiful Soup 从 <script> 中提取内容

python - 在 python 中找不到模块

python - 用python求解联立多元多项式方程

python - k样本的scipy Anderson-Darling测试中的数学溢出错误

python - 为什么我的正则表达式不能正确返回 group(0)?