【问题标题】:Scipy.optimize Constrained Minimization ErrorScipy.optimize 约束最小化误差
【发布时间】:2014-10-05 00:12:21
【问题描述】:

我试图在另外两个三个变量函数等于零的约束下最大化一个三变量函数 func(x,y,z)。

我正在关注http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html 中的“多元标量函数的约束最小化(最小化)”示例。我将目标函数更改为我自己的,并将程序调整为(我认为)运行三个变量而不是示例的两个变量。这是我的代码:

import numpy as np
from scipy.optimize import minimize

def zeroth(x):      # The form of the zeroth order contribution
    return x/(1+x**2)

def first(x):       # The form of the first order contribution
    return x/(1+x**2)**2 

def second(x):      # The second order contribution
    return x*(3-x**2)/(1+x**2)**3

def derivZeroth(x):
    return (1-x**2)/(1+x**2)**2

def derivFirst(x):
    return (1-3*x**2)/(1+x**2)**3

def derivSecond(x):
    return 3*(x**4 - 6*x**2 + 1)/(1+x**2)**4

def func(x, sign=1.0):
    """ Objective function """
    return  zeroth(x[0]) + zeroth(x[1]) - zeroth(x[2]) 

def func_deriv(x, sign=1.0):
    """ Derivative of objective function """
    dfdx0 = derivZeroth(x[0])
    dfdx1 = derivZeroth(x[1])
    dfdx2 = -derivZeroth(x[2])
    return np.array([ dfdx0, dfdx1, dfdx2 ])

cons = ({'type': 'eq',
         'fun' : lambda x: np.array([ first(x[0]) + first(x[1]) - first(x[2]) ]),
         'jac' : lambda x: np.array([ derivFirst(x[0]) + derivFirst(x[1]) - derivFirst(x[2])  ])},
        {'type': 'eq',
         'fun' : lambda x: np.array([ second(x[0]) + second(x[1]) - second(x[2]) ]),
         'jac' : lambda x: np.array([ derivSecond(x[0]) + derivSecond(x[1]) -  derivSecond(x[2]) ])})


x0 = [1.0,1.0,1.0]

res = minimize(func, x0, args=(-1.0,), jac=func_deriv,
           constraints=cons, method='SLSQP', options={'disp': True})





print(res.x)

我得到了错误

ValueError: all the input array dimensions except for the concatenation axis must match exactly

完整的错误如下所示:

Traceback (most recent call last):
  File "mycode.py", line 46, in <module>
    constraints=cons, method='SLSQP', options={'disp': True})
  File ".../python2.7/site-packages/scipy/optimize/_minimize.py", line 388, in minimize
    constraints, **options)
  File ".../python2.7/site-packages/scipy/optimize/slsqp.py", line 393, in _minimize_slsqp
    a = vstack((a_eq, a_ieq))
  File ".../python2.7/site-packages/numpy/core/shape_base.py", line 228, in vstack
    return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
ValueError: all the input array dimensions except for the concatenation axis must match exactly

发生了什么事?

【问题讨论】:

    标签: python optimization scipy constraints


    【解决方案1】:

    我认为约束的雅可比应该有长度 3。

    【讨论】:

    • 是的,就是这样,我添加它们而不是用逗号分隔。谢谢!
    猜你喜欢
    • 2019-03-12
    • 2020-07-27
    • 2020-09-04
    • 2013-12-03
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    相关资源
    最近更新 更多