繁体   English   中英

Scipy.optimize约束最小化误差

[英]Scipy.optimize Constrained Minimization Error

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

这是怎么回事?

我认为约束的雅各派成员应具有3的长度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM