问题描述
我需要一些关于python(scipy)优化函数的帮助问题是优化 f(x)
其中 x=[a,b,c...n]
.约束是 a、b 等的值应介于 0 和 1 之间,并且 sum(x)==1
.scipy.optimise.minimize 函数似乎最好,因为它不需要差分.我如何传递参数?
I need some help regarding optimisation functions in python(scipy)the problem is optimizing f(x)
where x=[a,b,c...n]
. the constraints are that values of a,b etc should be between 0 and 1, and sum(x)==1
. The scipy.optimise.minimize function seems best as it requires no differential. How do I pass the arguments?
使用排列创建 ndarray 太长了.我现在的代码如下:-
Creating an ndarray using permutation is too long. My present code as below:-
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
推荐答案
您可以使用 COBYLA
或 SLSQP
进行约束优化,正如 文档.
You can do a constrained optimization with COBYLA
or SLSQP
as it says in the 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)
将这些组合到最小化函数中.
Combine these into the minimization function.
res = minimize(getSharpe, start_pos, method='SLSQP', bounds=bnds ,constraints=cons)
这篇关于如何在有约束的 scipy 中使用最小化函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!