简体   繁体   English

scipy.optimize.minimize用于python中的约束优化

[英]scipy.optimize.minimize for constrained optimization in python

In the below problem I'm using scipy.optimize.minimize function to solve a constrained optimization problem with 5 parameters, named params . 在下面的问题中,我使用scipy.optimize.minimize函数来解决具有5个参数的约束优化问题,称为params When I debug my script in Python the optimal params returned a vector of 5- nan elements. 当我调试我的Python脚本的最佳PARAMS返回5- 元素的向量。 Any ideas? 有任何想法吗?

from scipy.optimize import minimize

xdata = np.arange(0, 17.5, 0.125)*0.1
xdata= xdata[60:85]
ydata = 1.0/xdata

plt.plot( xdata, ydata , 'ro', label='data')
plt.show()

def getvar(xobs, params) :
    yobs = np.asarray( [0.0]*len(xobs) )
    for i in range(len(xobs)):
        yobs[i] = params[0] + params[1] *(params[2]*(  math.log(xobs[i]) - params[3] ) +  math.sqrt( ( math.log(xobs[i]) - params[3]   )**2 + params[4]**2)  )
    return yobs

def resi(params):
    return getvar(xdata, params) - ydata


def sum_resi(params) :
    return sum( resi(params)**2 )

#Unconstrained
guess = np.asarray( [1.0,1.0,1.0,1.0,1.0] )
pwithout,cov,infodict,mesg,ier=scimin.leastsq(resiguess,full_output=True)

ylsq = getvar( xdata, pwithout)
plt.plot(xdata, ylsq,  'b--', label='fitted plot')
plt.show()

#Constrained: Use the guess from the unconstrained problem

cons = ( {'type': 'ineq','fun' : lambda params: np.array([params[0]       +   params[1]*params[4]* math.sqrt( 1 - params[2]**2 ) ]  )})
bnds = ( (None, None), (0, None), (-1,1),(None, None),(0, None) )
pwith=scimin.minimize(sum_resi,pwithout, method='SLSQP', bounds=bnds,
    constraints=cons, options={'disp': True})
ylsqconst = getvar( xdata, pwith.x) 
plt.plot(xdata, ylsqconst,  'g--', label='fitted plot')
plt.show()

Notes 笔记

You can see in each iteration that all parameters satisfy the conditions. 您可以在每次迭代中看到所有参数都满足条件。 Set a debug point at i) the line defining the constraints: cons = ( {'type': 'ineq','fun' ... and at ii) the line returning the sum of residuals: return sum(resi(params)**2 ) . 在i)定义约束的行上设置调试点: cons = ( {'type': 'ineq','fun' ...,在ii)返回残差之和的行: return sum(resi(params)**2 ) Please let me know if you can see an error that I can't see. 如果您可以看到我看不到的错误,请告诉我。

I think the issue might be a simple typo. 我认为问题可能是简单的错字。 In the line 在行中

pwithout,cov,infodict,mesg,ier=scimin.leastsq(resiguess,full_output=True)

shouldn't it be leastsq(resi, guess, ...) ? 难道不应该是leastsq(resi, guess, ...)吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM