Python SciPy IndexError:边界长度与x0的长度不兼容 [英] Python SciPy IndexError: the length of bounds is not compatible with that of x0
问题描述
我是使用Python和scipy进行优化的新手.我遇到了错误
I'm new to optimizations using Python and scipy. I'm getting the error
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的示例中的示例:
Notice in the example given in the docs for optimize.minimize:
>>> bnds = ((0, None), (0, None))
>>> res = minimize(fun, (2, 0), method='SLSQP', bounds=bnds,
... constraints=cons)
bnds
是一个元组序列. len(bnds)
等于初始猜测的长度x0
,在示例中为(2, 0)
.
that bnds
is a sequence of tuples. len(bnds)
equals the length of the initial guess, x0
, which in the example is (2, 0)
.
在您的代码中,bounds
是一个元组列表的元组.需要将其展平为一系列元组,例如
In your code bounds
is a tuple of lists of tuples. It needs to be flattened to a sequence of tuples, such as
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个项目:
Notice also that bnds is a list of 22 two-tuples, which is consistent with there
being 22 items in x0.flatten()
:
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 IndexError:边界长度与x0的长度不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!