非线性回归中的标准误差

syn*_*ing 7 python numpy gnuplot scipy

我一直用Python做一些蒙特卡罗物理模拟,我无法确定非线性最小二乘拟合系数的标准误差.

最初,我使用SciPy scipy.stats.linregress作为我的模型,因为我认为它将是一个线性模型,但注意到它实际上是某种功能函数.然后我使用NumPy的polyfit自由度为2,但无论如何我都找不到确定系数的标准误差.

我知道gnuplot可以为我确定错误,但我需要做适合超过30种不同的情况.我想知道是否有人知道Python无法从gnuplot读取标准错误或者是否有其他我可以使用的库?

syn*_*ing 11

终于找到了这个长问的答案!我希望这至少可以为这个话题节省几个小时的无望研究.Scipy在其优化部分下有一个名为curve_fit的特殊函数.它使用最小二乘法确定系数,最重要的是,它为您提供协方差矩阵.协方差矩阵包含每个系数的方差.更准确地说,矩阵的对角线是方差,通过平方根值,可以确定每个系数的标准误差!Scipy没有太多的文档,所以这里是一个示例代码,以便更好地理解:

import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plot


def func(x,a,b,c):
    return a*x**2 + b*x + c #Refer [1]

x = np.linspace(0,4,50)
y = func(x,2.6,2,3) + 4*np.random.normal(size=len(x)) #Refer [2] 


coeff, var_matrix = curve_fit(func,x,y)
variance = np.diagonal(var_matrix) #Refer [3]

SE = np.sqrt(variance) #Refer [4]

#======Making a dictionary to print results========
results = {'a':[coeff[0],SE[0]],'b':[coeff[1],SE[1]],'c':[coeff[2],SE[2]]}

print "Coeff\tValue\t\tError"
for v,c in results.iteritems():
    print v,"\t",c[0],"\t",c[1]
#========End Results Printing=================

y2 = func(x,coeff[0],coeff[1],coeff[2]) #Saves the y values for the fitted model

plot.plot(x,y)
plot.plot(x,y2)

plot.show()
Run Code Online (Sandbox Code Playgroud)
  1. 此函数返回的内容至关重要,因为它定义了适合模型的内容
  2. 使用该函数创建一些任意数据+一些噪音
  3. 将协方差矩阵的对角线保存为1D矩阵,这只是一个正常的阵列
  4. 平方根方差以获得标准误差(SE)


and*_*oke 2

看起来 gnuplot 使用levenberg - marquardt并且有一个可用的 python 实现- 您可以从 mpfit.covar 属性获取错误估计(顺便说一句,您应该担心错误估计的“平均值” - 是否允许调整其他参数以补偿, 例如?)