scipy.curve_fit与numpy.polyfit不同的协方差矩阵

use*_*000 6 python numpy curve-fitting scipy

我使用Python 3.6进行数据拟合.最近,我遇到了以下问题而且我缺乏经验,因此我不确定如何处理这个问题.

如果我在同一组数据点上使用numpy.polyfit(x,y,1,cov = True)和scipy.curve_fit(lambda:x,a,b:a*x + b,x,y),我得到系数a和b几乎相同.但是scipy.curve_fit的协方差矩阵的值大约是numpy.polyfit值的一半.

由于我想使用协方差矩阵的对角线来估计系数的不确定性(u = numpy.sqrt(numpy.diag(cov))),我有三个问题:

  1. 哪个协方差矩阵是正确的(我应该使用哪一个)?
  2. 为什么会有区别?
  3. 它需要什么来使它们平等?

谢谢!

编辑:

import numpy as np
import scipy.optimize as sc

data = np.array([[1,2,3,4,5,6,7],[1.1,1.9,3.2,4.3,4.8,6.0,7.3]]).T

x=data[:,0]
y=data[:,1]

A=np.polyfit(x,y,1, cov=True)
print('Polyfit:', np.diag(A[1]))

B=sc.curve_fit(lambda x,a,b: a*x+b, x, y)
print('Curve_Fit:', np.diag(B[1]))
Run Code Online (Sandbox Code Playgroud)

如果我使用statsmodels.api,结果对应于curve_fit的结果.

Dan*_*l F 2

我想这与此有关

593          # Some literature ignores the extra -2.0 factor in the denominator, but 
594          #  it is included here because the covariance of Multivariate Student-T 
595          #  (which is implied by a Bayesian uncertainty analysis) includes it. 
596          #  Plus, it gives a slightly more conservative estimate of uncertainty. 
597          if len(x) <= order + 2: 
598              raise ValueError("the number of data points must exceed order + 2 " 
599                               "for Bayesian estimate the covariance matrix") 
600          fac = resids / (len(x) - order - 2.0) 
601          if y.ndim == 1: 
602              return c, Vbase * fac 
603          else: 
604              return c, Vbase[:,:, NX.newaxis] * fac 
Run Code Online (Sandbox Code Playgroud)

在本例中,len(x) - order是 4 ,(len(x) - order - 2.0)是 2,这可以解释为什么您的值相差 2 倍。

这解释了问题 2。问题 3 的答案可能是“获取更多数据”,而对于较大的len(x)数据,差异可能可以忽略不计。

哪个公式是正确的(问题1)可能是Cross Validated 的问题,但我认为它是curve_fit为了明确计算您所说的不确定性。从文档中

pcov:二维数组

popt 的估计协方差。对角线提供参数估计的方差。要计算参数的一个标准差误差,请使用 perr = np.sqrt(np.diag(pcov))。

虽然上面代码中的注释polyfit表明其意图更多是针对 Student-T 分析。