我不熟悉使用 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/