Python SciPy IndexError: the length of bounds is not compatible with that of x0

Python SciPy IndexError: the length of bounds is not compatible with that of x0

我不熟悉使用 Python 和 scipy 进行优化。我收到错误

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

当试图将 bounds 参数传递给 scipy.optimize.minimize

x0 = np.array([[2,2,2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2,2,2,2]])
bounds = ( [(0,12000),(0,12000),(0,12000),(0,12000),(0,12000),(0,12000),(0,12000),(0,12000),(0,12000),(0,12000),(0,12000)], [(0,12000),(0,12000),(0,12000),(0,12000),(0,12000),(0,12000),(0,12000),(0,12000),(0,12000),(0,12000),(0,12000)] )

x_max = optimize.minimize(f, x0.flatten(), method='SLSQP', bounds=bounds)

对于这样的x0应该如何定义bounds

optimize.minimize 文档中给出的示例中的注意事项:

>>> bnds = ((0, None), (0, None))
>>> res = minimize(fun, (2, 0), method='SLSQP', bounds=bnds,
...                constraints=cons)

bnds是一个元组序列。 len(bnds) 等于初始猜测的长度 x0,在示例中为 (2, 0).


在您的代码中 bounds 是元组列表的元组。它需要被展平为一个元组序列,例如

bnds = bounds[0]+bounds[1]

或者,更简单地说,

bnds = [(0, 12000)]*22
x_max = optimize.minimize(f, x0.flatten(), method='SLSQP', bounds=bnds)

还要注意bnds是一个22个二元组的list,跟那里是一致的 x0.flatten() 中的 22 项:

In [19]: x0.flatten()
Out[19]: array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

In [20]: len(x0.flatten())
Out[20]: 22

我遇到了同样的错误,但原因不同。我尝试了一个仅针对一个输入变量进行优化的玩具示例。我的边界变量如下所示:

bnds=((0.0, 100.0))

我必须将其更改为以下内容才能使其正常工作:

bnds=((0.0, 100.0),)