numpy中的线性回归斜率误差

numpy中的线性回归斜率误差,numpy,linear-regression,standard-deviation,Numpy,Linear Regression,Standard Deviation,我使用numpy.polyfit得到一个线性回归:coeffs=np.polyfit(x,y,1) 使用numpy计算拟合斜率误差的最佳方法是什么?正如@ebarr在评论中提到的,您可以使用np.polyfit通过使用关键字参数full=True返回残差 例如: x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0]) z, residuals, rank, sing

我使用numpy.polyfit得到一个线性回归:coeffs=np.polyfit(x,y,1)


使用numpy计算拟合斜率误差的最佳方法是什么?

正如@ebarr在评论中提到的,您可以使用np.polyfit通过使用关键字参数
full=True
返回残差

例如:

x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
z, residuals, rank, singular_values, rcond = np.polyfit(x, y, 3, full=True)
x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
z, cov = np.polyfit(x, y, 3, cov=True)
残差
则是最小平方和

或者,您可以使用关键字参数
cov=True
来获取协方差矩阵

例如:

x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
z, residuals, rank, singular_values, rcond = np.polyfit(x, y, 3, full=True)
x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
z, cov = np.polyfit(x, y, 3, cov=True)
然后,
cov
的对角线元素是z中系数的方差,即
np.sqrt(np.diag(cov))
给出系数的标准偏差。您可以使用标准偏差来估计绝对误差超过某个值的概率,例如,通过在中插入标准偏差。如果在不确定度传播中使用例如3*标准偏差,则计算99.7%情况下不会超过的误差


最后一个提示:您必须选择是选择
full=True
还是
cov=True
cov=True
仅在
full=False
(默认)时有效,反之亦然。

使用
polyfit
时,它返回拟合的残差。你可以在这上面做一个Chi2来得到拟合优度,我假设这就是你要寻找的。我寻找的是绝对误差,而不是优度。残差是拟合中每个点的绝对误差。当我尝试实现这个解决方案时,我沿着协变量矩阵的对角线得到负值。