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'值的反应。 –