如果你有足够的数据点,你可以通过参数得到cov=True
估计的协方差矩阵polyfit()
。请记住,您可以写出多项式p[0]*t**n + p[1]*t**(n-1) + ... + p[n]
作为矩阵乘积np.dot(tt, p)
with tt=[t**n, tt*n-1, ..., 1]
. t
可以是单个值或列向量。由于这是一个线性方程,具有协方差矩阵C_p
of p
,值的协方差矩阵是np.dot(tt, np.dot(C_p tt.T))
.
一个简单的例子
import numpy as np
import matplotlib.pyplot as plt
# sample data:
x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0, -3.0])
n = 3 # degree of polynomial
p, C_p = np.polyfit(x, y, n, cov=True) # C_z is estimated covariance matrix
# Do the interpolation for plotting:
t = np.linspace(-0.5, 6.5, 500)
# Matrix with rows 1, t, t**2, ...:
TT = np.vstack([t**(n-i) for i in range(n+1)]).T
yi = np.dot(TT, p) # matrix multiplication calculates the polynomial values
C_yi = np.dot(TT, np.dot(C_p, TT.T)) # C_y = TT*C_z*TT.T
sig_yi = np.sqrt(np.diag(C_yi)) # Standard deviations are sqrt of diagonal
# Do the plotting:
fg, ax = plt.subplots(1, 1)
ax.set_title("Fit for Polynomial (degree {}) with $\pm1\sigma$-interval".format(n))
ax.fill_between(t, yi+sig_yi, yi-sig_yi, alpha=.25)
ax.plot(t, yi,'-')
ax.plot(x, y, 'ro')
ax.axis('tight')
fg.canvas.draw()
plt.show()
gives
请注意,计算完整矩阵C_yi
计算和记忆方面的效率不是很高。
Update- 根据@oliver-w 的请求,就方法论说几句话:
polyfit
假设参数x_i
是确定性的并且y_i
是与期望值不相关的随机变量y_i
和相同的方差sigma
。因此这是一个线性估计问题,可以使用普通的最小二乘法。通过确定残差的样本方差,sigma
可以近似。基于sigma
的协方差矩阵pp
可以计算如下维基百科关于最小二乘的文章 https://en.wikipedia.org/wiki/Least_squares#Least_squares.2C_regression_analysis_and_statistics。差不多就是这个方法polyfit()
用途: 用于sigma
更保守的因素S/(n-m-2)
代替S/(n-m)
用来。