【问题标题】:Specifying bounds for one dimensional optimization problem SciPy为一维优化问题 SciPy 指定界限
【发布时间】:2019-04-11 23:54:51
【问题描述】:

我有一个需要优化的一维函数。我的初始值为 20,边界为 (0,50)

  • x0=[20]
  • bounds=(0,50)
  • sol1=minimize(f,x0,method="SLSQP",bounds=bounds)

但是,这会产生 IndexError。

SLSQP Error: the length of bounds is not compatible with that of x0.

我在这里犯了什么错误?

【问题讨论】:

  • bounds=[(0,20)] ?
  • 另外,你可能应该使用minimize_scalar

标签: python python-3.x optimization scipy


【解决方案1】:

正如 cmets 中所指出的,您可以将边界放在一个列表中。一个最小的示例如下所示:

from scipy.optimize import minimize


def f(x):
    return (x - 3) ** 2

x0 = [10]
bounds = [(0, 50)]

res = minimize(f, x0, method='SLSQP', bounds=bounds)

然后res.x 将给出预期的array([3.])

正如cmets中@sascha所指出的,对于这种问题你也可以使用minimize_scalar

只需将上面的导入更改为

from scipy.optimize import minimize_scalar

并使用

res2 = minimize_scalar(f, method='bounded', bounds=bounds)

然后res2.x 返回3.0

只需将上面的f 替换为您的实际功能即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 2017-10-29
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    相关资源
    最近更新 更多