【问题标题】:Python SciPy IndexError: the length of bounds is not compatible with that of x0Python SciPy IndexError:边界的长度与x0的长度不兼容
【发布时间】:2015-03-19 16:30:11
【问题描述】:

我是使用 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

【问题讨论】:

    标签: python python-2.7 numpy scipy


    【解决方案1】:

    请注意优化文档中给出的示例中的示例:

    >>> 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
    

    【讨论】:

      【解决方案2】:

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

      bnds=((0.0, 100.0))
      

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

      bnds=((0.0, 100.0),)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-27
        • 1970-01-01
        • 2013-11-26
        • 2021-06-30
        相关资源
        最近更新 更多