如何在带有约束的 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

原文由 anand 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 603
1 个回答

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

原文由 Daniel 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题