如何从一维 Python 中的 polyfit 中获取最小二乘/误差的总和 [英] How to get the sum of least squares/error from polyfit in one dimension Python

查看:37
本文介绍了如何从一维 Python 中的 polyfit 中获取最小二乘/误差的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 polyfit 对散点图进行线性回归,并且我还想通过残差来查看线性回归的效果.但我不确定我是如何得到这个的,因为不可能从 polyfit 得到残差作为输出值,因为这是一维的.我的代码:

I want to do a linear regression for a scatter plot using polyfit, and I also want the residual to see how good the linear regression is. But I am unsure how I get this as it isn't possible to get the residual as an output value from polyfit since this is one dimensional. My code:

p = np.polyfit(lengths, breadths, 1)
m = p[0]
b = p[1]
yfit = np.polyval(p,lengths)
newlengths = []
for y in lengths:
    newlengths.append(y*m+b)
ax.plot(lengths, newlengths, '-', color="#2c3e50")

我看到了一个 stackoverflow 的答案,他们使用了 polyval - 但我不确定这给了我什么.这是长度的确切值吗?我应该通过从 polyval 和 'breadth' 中找到每个元素的 delta 来找出错误吗?

I saw a stackoverflow answer where they used polyval - but I am unsure of what that gives me. Is that the exact values for the lengths? Should I find the error by finding the delta of each element from the polyval and 'breadth'?

推荐答案

您可以在调用 polyfit 时使用关键字 full=True(请参阅 http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html) 以获得拟合的最小二乘误差:

You can use the keyword full=True when calling polyfit (see http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html) to get the least-square error of your fit:

coefs, residual, _, _, _ = np.polyfit(lengths, breadths, 1, full=True)

您可以通过以下方式获得相同的答案:

You can get the same answer by doing:

coefs = np.polyfit(lengths, breadths, 1)
yfit = np.polyval(coefs,lengths)
residual = np.sum((breadths-yfit)**2)

residual = np.std(breadths-yfit)**2 * len(breadths)

另外,如果你想绘制残差,你可以这样做:

Additionally, if you want to plot the residuals, you can do:

coefs = np.polyfit(lengths, breadths, 1)
yfit = np.polyval(coefs,lengths)
plot(lengths, breadths-yfit)

这篇关于如何从一维 Python 中的 polyfit 中获取最小二乘/误差的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆