Python - 计算有错误的趋势线
因此,我将一些数据存储为两个列表,并使用
plot(datasetx, datasety)
然后我设置了趋势线
trend = polyfit(datasetx, datasety)
trendx = []
trendy = []
for a in range(datasetx[0], (datasetx[-1]+1)):
trendx.append(a)
trendy.append(trend[0]*a**2 + trend[1]*a + trend[2])
plot(trendx, trendy)
来绘制它们,但是我有第三个数据列表,这是原始数据集中的错误。我可以很好地绘制误差线,但我不知道如何使用它,如何找到多项式趋势线系数中的误差。
假设我的趋势线是 5x^2 + 3x + 4 = y,那么 5、3 和 4 值上肯定存在某种错误。
有没有使用 NumPy 的工具可以为我计算这个?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你可以使用 scipy.optimize 的函数
curve_fit
(文档)。一个基本的用法示例:根据文档,pcov 给出:
因此,通过这种方式,您可以计算系数的误差估计。要获得标准差,您可以取方差的平方根。
现在系数有误差,但它仅基于 ydata 和拟合之间的偏差。如果您还想考虑 ydata 本身的错误,
curve_fit
函数提供sigma
参数:一个完整的示例:
然后是其他内容,关于使用 numpy 数组。使用 numpy 的主要优点之一是可以避免 for 循环,因为数组上的操作按元素应用。因此,示例中的 for 循环也可以按以下方式完成:
我使用
arange
而不是 range,因为它返回 numpy 数组而不是列表。在这种情况下,您还可以使用 numpy 函数
polyval
:I think you can use the function
curve_fit
ofscipy.optimize
(documentation). A basic example of the usage:Following the documentation, pcov gives:
So in this way you can calculate an error estimate on the coefficients. To have the standard deviation you can take the square root of the variance.
Now you have an error on the coefficients, but it is only based on the deviation between the ydata and the fit. In case you also want to account for an error on the ydata itself, the
curve_fit
function provides thesigma
argument:A complete example:
Then something else, about using numpy arrays. One of the main advantages of using numpy is that you can avoid for loops because operations on arrays apply elementwise. So the for-loop in your example can also be done as following:
Where I use
arange
instead of range as it returns a numpy array instead of a list.In this case you can also use the numpy function
polyval
:我还没有找到任何方法来获取 numpy 或 python 内置系数中的错误。我有一个简单的工具,是根据 John Taylor 的错误分析简介的第 8.5 节和 8.6 节编写的。也许这足以满足您的任务(请注意,默认返回是方差,而不是标准差)。由于显着的协方差,您可能会得到很大的错误(如提供的示例中所示)。
I have not been able to find any way of getting the errors in the coefficients that is built in to numpy or python. I have a simple tool that I wrote based on Section 8.5 and 8.6 of John Taylor's An Introduction to Error Analysis. Maybe this will be sufficient for your task (note the default return is the variance, not the standard deviation). You can get large errors (as in the provided example) because of significant covariance.