一维优化问题SciPy的边界指定

2024-09-28 22:28:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

但是,这会产生一个索引器。在

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

我在这里犯了什么错误?在


Tags: ofthe函数isnoterrorlengthmethod
1条回答
网友
1楼 · 发布于 2024-09-28 22:28:20

正如在评论中指出的,你可以把界限放在一个列表中。一个最小的例子如下:

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.])。在

正如@sascha在评论中指出的,对于此类问题,您也可以使用^{}

只需将上面的导入更改为

^{pr2}$

和使用

^{3}$

然后res2.x返回3.0

只需将上面的f替换为实际函数。在

相关问题 更多 >