Python SciPy 索引错误 : the length of bounds is not compatible with that of x0

标签 python python-2.7 numpy scipy

我不熟悉使用 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个二元组的列表,和那里是一致的 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

关于Python SciPy 索引错误 : the length of bounds is not compatible with that of x0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29150064/

相关文章:

python - 使用 numpy 进行音高插值

python - 系列的长度与 np.where 不匹配

python - python 上的简单正则表达式

python - 将整数数组转换为 unicode

python - 如何按行获取 numpy 数组的非零元素数?

python - 使用另一个数组更改数组的形状

具有积分函数的python拟合曲线

python - 如何获取由双叉创建的守护进程的 pid?

python - Webscraping NSE Options prices using Python BeautifulSoup,关于编码校正

python - python 中的整数与 float :Cannot understand the behavior