问题描述
我有一个使用 SciPy 的 leastsq
函数拟合的数据表面.
I have a data surface that I'm fitting using SciPy's leastsq
function.
我想对 leastsq
返回后的拟合质量进行一些估计.我原以为这会作为函数的返回包含在内,但如果是这样,它似乎没有明确记录.
I would like to have some estimate of the quality of the fit after leastsq
returns. I'd expected that this would be included as a return from the function, but, if so, it doesn't seem to be clearly documented.
是否有这样的返回,或者,除此之外,我可以将数据和返回的参数值以及拟合函数传递给某些函数,以便对拟合质量进行估计(R^2 或类似的)?
Is there such a return or, barring that, some function I can pass my data and the returned parameter values and fit function to that will give me an estimate of fit quality (R^2 or some such)?
谢谢!
推荐答案
如果你这样调用 leastsq
:
import scipy.optimize
p,cov,infodict,mesg,ier = optimize.leastsq(
residuals,a_guess,args=(x,y),full_output=True)
哪里
def residuals(a,x,y):
return y-f(x,a)
然后,使用 R^2
的定义给定 here,
then, using the definition of R^2
given here,
ss_err=(infodict['fvec']**2).sum()
ss_tot=((y-y.mean())**2).sum()
rsquared=1-(ss_err/ss_tot)
你问什么是 infodict['fvec']
?这是残差数组:
In [48]: optimize.leastsq?
...
infodict -- a dictionary of optional outputs with the keys:
'fvec' : the function evaluated at the output
例如:
import scipy.optimize as optimize
import numpy as np
import collections
import matplotlib.pyplot as plt
x = np.array([821,576,473,377,326])
y = np.array([255,235,208,166,157])
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=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))
pxp=sigmoid(p,xp)
# You could compute the residuals this way:
resid=residuals(p,x,y)
print(resid)
# [ 0.76205302 -2.010142 2.60265297 -3.02849144 1.6739274 ]
# But you don't have to compute `resid` -- `infodict['fvec']` already
# contains the info.
print(infodict['fvec'])
# [ 0.76205302 -2.010142 2.60265297 -3.02849144 1.6739274 ]
ss_err=(infodict['fvec']**2).sum()
ss_tot=((y-y.mean())**2).sum()
rsquared=1-(ss_err/ss_tot)
print(rsquared)
# 0.996768131959
plt.plot(x, y, '.', xp, pxp, '-')
plt.xlim(100,1000)
plt.ylim(130,270)
plt.xlabel('x')
plt.ylabel('y',rotation='horizontal')
plt.grid(True)
plt.show()
这篇关于SciPy LeastSq 拟合优度估计器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!