Scipy.optimize约束最小化错误

时间:2014-10-05 00:12:21

标签: python optimization scipy constraints

我试图在另外三个变量函数等于零的约束下最大化三变量函数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

发生了什么事?

1 个答案:

答案 0 :(得分:2)

我认为约束的jacobians应该有3个长度。