我正在尝试优化以下功能:
f(x,a+,a-,b) = a+*((1/(1+exp(-b*x)) - 1/2) if x>=0
= a-*((1/1+exp(-b*x)) -1/2) if x<0
constraints: a+ * b <=4, a-*b <=4
a+/2 <= max(if(x>0))
a-/2 <= -min(if(x<0))
我试图通过设置边界 [(0,2), (0,2), (1,None)] 和上面定义的约束来使用 scpiy 中的最小化函数,但是该函数没有提供正确的结果,特别是如果我使用 beta 作为约束中的参数。
from scipy.optimize import minimize
init_params=[0.0,0.0,20.0]
bnds = [(0.0,2.0), (0.0,2.0), (1.0,None)]
S_curve = pd.DataFrame()
S_curve['year'] = dfs2.index
S_curve['H_Change'] = np.array(dfs2.loc[:,'annualH_chg'])
S_curve['R_Change'] = np.array(dfs2.loc[:,'annualR_chg'])
S_curve['Weight'] = 1
S_curve.reset_index(drop=True)
weighted = S_curve[S_curve.Weight !=0]
minimum = -S_curve['R_Change'].min()
maximum = S_curve['R_Change'].max()
beta=init_params[2]
def constraint1(up, beta):
return 4.0-(up*beta)
def constraint2(down, beta):
return 4.0-(down*beta)
def constraint3(up, maximum):
return maximum - up/2.0
def constraint4(down, minimum):
return minimum - down/2.0
cons = [{'type':'ineq', 'fun':constraint1, 'args':(beta,)},
{'type':'ineq', 'fun':constraint2, 'args':(beta,)},
{'type':'ineq', 'fun':constraint3, 'args':(maximum,)},
{'type':'ineq', 'fun':constraint4, 'args':(minimum,)}]
soln = minimize(func, init_params, bounds=bnds, constraints=cons, method='SLQSP')
期望满足第一个和第二个约束,并且 beta (b) 不是恒定的。