如何从scipy.optimize.leastsq模块获取RMSE

时间:2010-12-23 16:53:27

标签: python numpy scipy

我可以从scipy.optimize.leastsq模块获取RMSE的值吗?

1 个答案:

答案 0 :(得分:5)

以下是使用leastsq的一个小例子:

import numpy as np
import scipy.optimize as optimize
import collections

x = np.array([821,576,473,377,326,300])
y = np.array([255,235,208,166,157,140])

def sigmoid(p,x):
    x0,y0,c,k=p
    y = c / (1 + np.exp(-k*(x-x0))) + y0
    return y

def residuals(p,x,y):
    return y - sigmoid(p,x)

Param=collections.namedtuple('Param','x0 y0 c k')
p_guess=Param(x0=600,y0=200,c=100,k=0.01)
p,cov,infodict,mesg,ier = optimize.leastsq(
    residuals,p_guess,args=(x,y),full_output=1,warning=True)
p=Param(*p)
xp = np.linspace(100, 1600, 1500)
print('''\
x0 = {p.x0}
y0 = {p.y0}
c = {p.c}
k = {p.k}
'''.format(p=p))

您可以通过这种方式计算残差:

resid=residuals(p,x,y)
print(resid)
# [ 0.76205302 -2.010142    2.60265297 -3.02849144  1.6739274 ]

但您无需计算resid - infodict['fvec']已包含该信息。

print(infodict['fvec'])
# [ 0.76205302 -2.010142    2.60265297 -3.02849144  1.6739274 ]

chisq=(infodict['fvec']**2).sum()
# dof is degrees of freedom
dof=len(x)-len(p)
rmse=np.sqrt(chisq/dof)
print(rmse)
# 5.40092057562