18

我需要一些关于 python(scipy) 中优化函数的帮助,问题是优化f(x)where 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
4

2 回答 2

30

您可以使用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)

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

res = minimize(getSharpe, start_pos, method='SLSQP', bounds=bnds ,constraints=cons)
于 2013-09-12T16:37:21.307 回答
7

检查.minimize文档字符串:

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)where g(x)is a function达到它的最小值 when sum(x)=1。比如g=lambda x: (sum(x)-1)**2

h(x)f(x)和都处于最小值时达到g(x)最小值。拉格朗日乘数法的一种情况http://en.wikipedia.org/wiki/Lagrange_multiplier

于 2013-09-12T15:37:15.920 回答