[英]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.