2
在Python中,使用SciPy,我需要找到函數的最大值Q*((1+y)*2-3*Q-0.1)-y**2
給定了限制(1-z)*(Q*((1+y)*2-3*Q-0.1))-y**2=0
。對於z
我想輸入一些值來找到最大化函數的參數,給定的值爲z
。python中的約束優化
我已經嘗試了很多方法來使用SciPy優化功能,但我無法弄清楚如何去做這件事。我使用WolframAlpha成功地做到了這一點,但這並沒有爲我提供這個問題後續問題的答案。
嘗試:
from scipy.optimize import minimize
def equilibrium(z):
#Objective function
min_prof = lambda(Q,y): -1*(Q*((1+y)*2-3*Q-0.1)-y**2)
#initial guess
x0 = (0.6,0.9)
#Restriction function
cons = ({'type': 'eq', 'fun': lambda (Q,y): (1-z)*(Q*((1+y)*2-3*Q-0.1))-y**2})
#y between 0 and 1, Q between 0 and 4
bnds = ((0,4),(0,1))
res = minimize(min_prof,x0, method='SLSQP', bounds=bnds ,constraints=cons)
return res.x
from numpy import arange
range_z = arange(0,1,0.001)
print equilibrium(range_z)
錯誤:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-20-527013574373> in <module>()
21 range_z = arange(0,1,0.01)
22
---> 23 print equilibrium(range_z)
<ipython-input-20-527013574373> in equilibrium(z)
14 bnds = ((0,4),(0,1))
15
---> 16 res = minimize(min_prof,x0, method='SLSQP', bounds=bnds ,constraints=cons)
17
18 return res.x
/Users/Joost/anaconda/lib/python2.7/site-packages/scipy/optimize/_minimize.pyc in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
456 elif meth == 'slsqp':
457 return _minimize_slsqp(fun, x0, args, jac, bounds,
--> 458 constraints, callback=callback, **options)
459 elif meth == 'dogleg':
460 return _minimize_dogleg(fun, x0, args, jac, hess,
/Users/Joost/anaconda/lib/python2.7/site-packages/scipy/optimize/slsqp.pyc in _minimize_slsqp(func, x0, args, jac, bounds, constraints, maxiter, ftol, iprint, disp, eps, callback, **unknown_options)
324 + 2*meq + n1 + ((n+1)*n)//2 + 2*m + 3*n + 3*n1 + 1
325 len_jw = mineq
--> 326 w = zeros(len_w)
327 jw = zeros(len_jw)
328
ValueError: negative dimensions are not allowed
上面的鏈接提供了一個執行約束優化的例子。如果您嘗試解決您的問題並遇到問題,請分享您的代碼嘗試,以及遇到的具體錯誤,我們可以從此處獲得幫助。 – CoryKramer
@CoryKramer我改述了我的問題,現在我爲'z'(這是0.3)獲得了一個特定值的解決方案,現在我想研究這些最優值對'z'值的反應。 –