在下面的问题中,我使用scipy.optimize.minimize
函数解决了一个名为params
的5个参数的约束优化问题。当我在Python中调试我的脚本时,最佳参数返回了一个5- nan 元素的向量。有什么想法吗?
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()
您可以在每次迭代中看到所有参数都满足条件。在i)定义约束的行:cons = ( {'type': 'ineq','fun'
...和ii)返回残差总和的行:return sum(resi(params)**2 )
。如果您能看到我无法看到的错误,请与我们联系。
答案 0 :(得分:0)
我认为问题可能是一个简单的错字。在行
pwithout,cov,infodict,mesg,ier=scimin.leastsq(resiguess,full_output=True)
不应该是leastsq(resi, guess, ...)
?