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

时间:2013-09-12 14:54:40

标签: 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

2 个答案:

答案 0 :(得分:21)

您可以使用COBYLASLSQP进行约束优化,如docs中所述。

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)

将这些结合到最小化函数中。

res = minimize(getSharpe, start_pos, method='SLSQP', bounds=bnds ,constraints=cons)

答案 1 :(得分:7)

检查.minimize docstring:

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

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

bounds=((0,1), (0,1).....)

现在,另一部分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

的情况进行排序
相关问题