如何在带有约束的scipy中使用最小化函数

ana*_*and 17 python optimization numpy scipy

我需要一些关于python(scipy)中优化函数的帮助,问题是优化f(x)在哪里x=[a,b,c...n].约束是a,b等的值应该在0和1之间,并且sum(x)==1.scipy.optimise.minimize函数似乎最好,因为它不需要差异.我如何传递参数?

使用排列创建一个ndarray太长了.我现在的代码如下: -

import itertools as iter
all=iter.permutations([0.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0],6) if sum==1
all_legal=[]
for i in all:
if np.sum(i)==1:
    #print np.sum(i)
    all_legal.append(i)
print len(all_legal)
lmax=0
sharpeMax=0
for i in all_legal:
    if sharpeMax<getSharpe(i):
        sharpeMax=getSharpe(i)
        lmax=i
Run Code Online (Sandbox Code Playgroud)

Dan*_*iel 22

您可以使用COBYLASLSQP文档中进行约束优化.

from scipy.optimize import minimize

start_pos = np.ones(6)*(1/6.) #or whatever

#Says one minus the sum of all variables must be zero
cons = ({'type': 'eq', 'fun': lambda x:  1 - sum(x)})

#Required to have non negative values
bnds = tuple((0,1) for x in start_pos)
Run Code Online (Sandbox Code Playgroud)

将这些结合到最小化功能中.

res = minimize(getSharpe, start_pos, method='SLSQP', bounds=bnds ,constraints=cons)
Run Code Online (Sandbox Code Playgroud)

  • `sum(k表示x中的k)`也称为`sum(x)`.:) (19认同)
  • @Dougal多年后,当我收到关于这个答案的通知时,我仍然对此表示赞同. (13认同)

CT *_*Zhu 7

检查.minimizedocstring:

scipy.optimize.minimize(fun, x0, args=(), method='BFGS', jac=None, hess=None, hessp=None, \
              bounds=None, constraints=(), tol=None, callback=None, options=None)
Run Code Online (Sandbox Code Playgroud)

在你的情况下最重要的是bounds.如果要在[0,1](或(0,1)?)中约束参数,则需要为每个变量定义它,例如:

bounds=((0,1), (0,1).....)
Run Code Online (Sandbox Code Playgroud)

现在,另一部分,sum(x)==1.可能有更优雅的方式来做到这一点,但考虑这一点:不是最小化f(x),可以大大降低h=lambda x: f(x)+g(x),新的功能所必需的f(x)+g(x),其中g(x)是一个函数达到它最低的时候sum(x)=1.如g=lambda x: (sum(x)-1)**2.

最小h(x)达到当两个f(x)g(x)处于最小.拉格朗日乘数法的一种情况排序http://en.wikipedia.org/wiki/Lagrange_multiplier