我有一组数据(位移与时间),我用optimize.leatsq方法将其拟合到了几个方程中。我现在正在寻找拟合参数的误差值。通过查阅文档,输出的矩阵是雅可比矩阵,我必须将它乘以剩余矩阵来得到我的值。不幸的是,我不是一个统计学家,所以我有点被术语淹没了。
根据我的理解,我只需要协方差矩阵和我的拟合参数,所以我可以平方根对角线元素得到我的标准误差的拟合参数。我模糊地记得,协方差矩阵是optimize.leatsq方法的输出。是这样吗?如果不是,你如何得到剩余矩阵乘以输出的雅可比矩阵得到我的协方差矩阵?
任何帮助都将不胜感激。我对python很陌生,因此如果问题是一个基本的问题,我会道歉。
装配代号如下:
fitfunc = lambda p, t: p[0]+p[1]*np.log(t-p[2])+ p[3]*t # Target function'
errfunc = lambda p, t, y: (fitfunc(p, t) - y)# Distance to the target function
p0 = [ 1,1,1,1] # Initial guess for the parameters
out = optimize.leastsq(errfunc, p0[:], args=(t, disp,), full_output=1)
args t和disp是时间和显示值的数组(基本上只有两列数据)。我已经导入了代码顶部需要的所有内容。输出提供的拟合值和矩阵如下:
[ 7.53847074e-07 1.84931494e-08 3.25102795e+01 -3.28882437e-11]
[[ 3.29326356e-01 -7.43957919e-02 8.02246944e+07 2.64522183e-04]
[ -7.43957919e-02 1.70872763e-02 -1.76477289e+07 -6.35825520e-05]
[ 8.02246944e+07 -1.76477289e+07 2.51023348e+16 5.87705672e+04]
[ 2.64522183e-04 -6.35825520e-05 5.87705672e+04 2.70249488e-07]]
我怀疑现在的情况有点可疑。当我能把错误说出来时,这将得到证实。
在线性回归的情况下,准确地计算误差是可能的。实际上leatsq函数给出了不同的值:
输出:
有趣的是,curvefit和bootstrap的结果会给。。。
在试图回答我自己类似的问题时发现了你的问题。 简短的回答。leatsq输出的
cov_x
应该乘以剩余方差。i、 e如
curve_fit.py
所示。这是因为leatsq输出分数协方差矩阵。我最大的问题是,当我在google上搜索时,残差会显示为其他东西。残差方差是简单地从你的拟合卡方减少。
2016年4月6日更新
在大多数情况下,在拟合参数中获得正确的错误是很微妙的。
让我们考虑拟合一个函数
y=f(x)
,对于这个函数,您有一组数据点(x_i, y_i, yerr_i)
,其中i
是在每个数据点上运行的索引。在大多数物理测量中,误差
yerr_i
是测量装置或程序的系统不确定度,因此可以认为它是一个不依赖于i
的常数。使用哪种拟合函数,如何获得参数误差?
optimize.leastsq
方法将返回分数协方差矩阵。将该矩阵的所有元素乘以剩余方差(即减小的卡方)并取对角元素的平方根,将得到拟合参数的标准偏差估计值。我已经在下面的一个函数中包含了这样做的代码。另一方面,如果使用
optimize.curvefit
,则上述过程的第一部分(乘以缩减的卡方)是在幕后为您完成的。然后需要取协方差矩阵对角线元素的平方根,以获得拟合参数的标准偏差估计值。此外,
optimize.curvefit
提供可选参数来处理更一般的情况,其中每个数据点的yerr_i
值不同。从documentation:我怎样才能确定我的错误是正确的?
确定合适的拟合参数标准误差估计是一个复杂的统计问题。由
optimize.curvefit
和optimize.leastsq
实现的协方差矩阵的结果实际上依赖于关于误差概率分布和参数之间相互作用的假设;可能存在的相互作用,取决于特定的拟合函数f(x)
。在我看来,处理复杂的
f(x)
的最佳方法是使用bootstrap方法,如this link所述。让我们看一些例子
首先,一些样板代码。让我们定义一个曲线函数并生成一些带有随机错误的数据。我们将生成一个带有小随机误差的数据集。
现在,让我们使用各种可用的方法来拟合函数:
`优化.租赁
`优化.曲线拟合`
`引导`
观察
我们已经开始看到一些有趣的东西,三种方法的参数和误差估计几乎一致。太好了!
现在,假设我们想告诉拟合函数,在我们的数据中还有一些其他的不确定性,可能是一个系统性的不确定性,它会造成20倍于
err_stdev
值的额外误差。实际上,如果我们用这种错误来模拟一些数据,它看起来会是这样的:我们当然不希望用这种噪声水平来恢复拟合参数。
首先,让我们认识到
leastsq
甚至不允许我们输入这个新的系统错误信息。让我们看看curve_fit
当我们告诉它错误时会做什么:什么??这肯定是错的!
这曾经是故事的结尾,但最近
curve_fit
添加了absolute_sigma
可选参数:这有点好,但还是有点可疑。
curve_fit
认为我们可以在p1
参数中以10%的误差拟合出噪声信号。让我们看看bootstrap
要说什么:啊,这也许是对拟合参数误差的更好估计。
bootstrap
认为它知道p1
,不确定度约为34%。摘要
optimize.leastsq
和optimize.curvefit
为我们提供了一种估计拟合参数误差的方法,但我们不能只使用这些方法而不稍微质疑它们。bootstrap
是一种使用暴力的统计方法,在我看来,它有一种在可能更难解释的情况下更好地工作的趋势。我强烈建议查看一个特定的问题,并尝试
curvefit
和bootstrap
。如果它们相似,那么curvefit
计算起来要便宜得多,因此可能值得使用。如果它们有显著的不同,那么我的钱就在bootstrap
上。相关问题 更多 >
编程相关推荐