如何使用 Python 和 Numpy 计算 r 平方?
我正在使用 Python 和 Numpy 来计算任意次数的最佳拟合多项式。 我传递 x 值、y 值和我想要拟合的多项式次数(线性、二次等)的列表。
这很有效,但我还想计算 r(相关系数)和 r 平方(确定系数)。 我将我的结果与 Excel 的最佳拟合趋势线功能及其计算的 r 平方值进行比较。 使用这个,我知道我正在正确计算线性最佳拟合的 r 平方(度等于 1)。 但是,我的函数不适用于次数大于 1 的多项式。Excel
可以做到这一点。 如何使用 Numpy 计算高阶多项式的 r 平方?
这是我的功能:
import numpy
# Polynomial Regression
def polyfit(x, y, degree):
results = {}
coeffs = numpy.polyfit(x, y, degree)
# Polynomial Coefficients
results['polynomial'] = coeffs.tolist()
correlation = numpy.corrcoef(x, y)[0,1]
# r
results['correlation'] = correlation
# r-squared
results['determination'] = correlation**2
return results
I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).
This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determination). I am comparing my results with Excel's best-fit trendline capability, and the r-squared value it calculates. Using this, I know I am calculating r-squared correctly for linear best-fit (degree equals 1). However, my function does not work for polynomials with degree greater than 1.
Excel is able to do this. How do I calculate r-squared for higher-order polynomials using Numpy?
Here's my function:
import numpy
# Polynomial Regression
def polyfit(x, y, degree):
results = {}
coeffs = numpy.polyfit(x, y, degree)
# Polynomial Coefficients
results['polynomial'] = coeffs.tolist()
correlation = numpy.corrcoef(x, y)[0,1]
# r
results['correlation'] = correlation
# r-squared
results['determination'] = correlation**2
return results
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
回复很晚,但以防万一有人需要一个现成的函数:
scipy.stats.linregress
即
如 @Adam Marples 的回答。
A very late reply, but just in case someone needs a ready function for this:
scipy.stats.linregress
i.e.
as in @Adam Marples's answer.
来自 yanl (yet-another-library)
sklearn.metrics
有一个r2_score
函数;From yanl (yet-another-library)
sklearn.metrics
has anr2_score
function;从 numpy.polyfit 文档中,它是拟合线性的回归。 具体来说,度为“d”的 numpy.polyfit 拟合线性回归,其平均函数
E(y|x) = p_d * x**d + p_{d-1} * x **(d-1) + .. . + p_1 * x + p_0
因此您只需计算该拟合的 R 平方。 线性回归上的维基百科页面提供了完整的详细信息。 您对 R^2 感兴趣,您可以通过多种方式计算它,最简单的可能是
我使用“y_bar”作为 y 的平均值,使用“y_ihat”作为每个点的拟合值。
我对 numpy 不太熟悉(我通常在 R 中工作),所以可能有一种更简洁的方法来计算 R 平方,但以下应该是正确的
From the numpy.polyfit documentation, it is fitting linear regression. Specifically, numpy.polyfit with degree 'd' fits a linear regression with the mean function
E(y|x) = p_d * x**d + p_{d-1} * x **(d-1) + ... + p_1 * x + p_0
So you just need to calculate the R-squared for that fit. The wikipedia page on linear regression gives full details. You are interested in R^2 which you can calculate in a couple of ways, the easisest probably being
Where I use 'y_bar' for the mean of the y's, and 'y_ihat' to be the fit value for each point.
I'm not terribly familiar with numpy (I usually work in R), so there is probably a tidier way to calculate your R-squared, but the following should be correct
我已经成功地使用了它,其中 x 和 y 是类似数组的。
注意:仅适用于线性回归
I have been using this successfully, where x and y are array-like.
Note: for linear regression only
我最初发布下面的基准测试的目的是推荐
numpy.corrcoef
,愚蠢地没有意识到原来的问题已经使用了corrcoef
并且实际上是在询问高阶多项式拟合。 我使用 statsmodels 添加了多项式 r 平方问题的实际解决方案,并且保留了原始基准,虽然偏离主题,但对某人可能有用。statsmodels
能够直接计算多项式拟合的r^2
,这里有 2 种方法...要进一步利用
statsmodels
,还应该查看拟合模型摘要,它可以在 Jupyter/IPython 笔记本中打印或显示为丰富的 HTML 表格。 除了 rsquared 之外,结果对象还提供对许多有用统计指标的访问。下面是我原来的答案,我对各种线性回归 r^2 方法进行了基准测试...
corrcoef函数计算相关系数
r
,仅适用于单个线性回归,因此它没有解决r^2的问题
用于高阶多项式拟合。 然而,无论如何,我发现对于线性回归来说,它确实是计算 r 的最快、最直接的方法。这些是我通过比较 1000 个随机 (x, y) 点的一堆方法得到的 timeit 结果:
r
计算)r
计算)r
计算)r
作为输出的线性回归)corrcoef 方法以微弱优势胜过使用 numpy 方法“手动”计算 r^2。 它比 polyfit 方法快 5 倍以上,比 scipy.linregress 快约 12 倍。 为了强调 numpy 为您所做的事情,它比纯 python 快 28 倍。 我不太熟悉 numba 和 pypy 之类的东西,所以其他人必须填补这些空白,但我认为这足以让我相信
corrcoef
是计算的最佳工具>r
用于简单的线性回归。这是我的基准测试代码。 我从 Jupyter Notebook 复制粘贴(很难不称其为 IPython Notebook...),所以如果途中出现任何问题,我深表歉意。 %timeit 魔术命令需要 IPython。
21 年 7 月 28 日基准测试结果。 (Python 3.7、numpy 1.19、scipy 1.6、statsmodels 0.12)
I originally posted the benchmarks below with the purpose of recommending
numpy.corrcoef
, foolishly not realizing that the original question already usescorrcoef
and was in fact asking about higher order polynomial fits. I've added an actual solution to the polynomial r-squared question using statsmodels, and I've left the original benchmarks, which while off-topic, are potentially useful to someone.statsmodels
has the capability to calculate ther^2
of a polynomial fit directly, here are 2 methods...To further take advantage of
statsmodels
, one should also look at the fitted model summary, which can be printed or displayed as a rich HTML table in Jupyter/IPython notebook. The results object provides access to many useful statistical metrics in addition torsquared
.Below is my original Answer where I benchmarked various linear regression r^2 methods...
The corrcoef function used in the Question calculates the correlation coefficient,
r
, only for a single linear regression, so it doesn't address the question ofr^2
for higher order polynomial fits. However, for what it's worth, I've come to find that for linear regression, it is indeed the fastest and most direct method of calculatingr
.These were my timeit results from comparing a bunch of methods for 1000 random (x, y) points:
r
calculation)r
calculation)r
calculation)r
as an output)The corrcoef method narrowly beats calculating the r^2 "manually" using numpy methods. It is >5X faster than the polyfit method and ~12X faster than the scipy.linregress. Just to reinforce what numpy is doing for you, it's 28X faster than pure python. I'm not well-versed in things like numba and pypy, so someone else would have to fill those gaps, but I think this is plenty convincing to me that
corrcoef
is the best tool for calculatingr
for a simple linear regression.Here's my benchmarking code. I copy-pasted from a Jupyter Notebook (hard not to call it an IPython Notebook...), so I apologize if anything broke on the way. The %timeit magic command requires IPython.
7/28/21 Benchmark results. (Python 3.7, numpy 1.19, scipy 1.6, statsmodels 0.12)
这是一个使用 Python 和 Numpy 计算加权 r 平方的函数(大部分代码来自 sklearn):
示例:
输出:
这对应于 公式 (镜像):
其中 f_i 是拟合的预测值,y_{av} 是观测数据的平均值,y_i 是观测数据值。 w_i是应用于每个数据点的权重,通常w_i=1。 SSE 是误差平方和,SST 是总平方和。
如果有兴趣,R中的代码: https://gist.github.com/dhimmel/588d64a73fa4fef02c8f (镜像)
Here is a function to compute the weighted r-squared with Python and Numpy (most of the code comes from sklearn):
Example:
outputs:
This corresponds to the formula (mirror):
with f_i is the predicted value from the fit, y_{av} is the mean of the observed data y_i is the observed data value. w_i is the weighting applied to each data point, usually w_i=1. SSE is the sum of squares due to error and SST is the total sum of squares.
If interested, the code in R: https://gist.github.com/dhimmel/588d64a73fa4fef02c8f (mirror)
这是一个非常简单的 python 函数,假设 y 和 y_hat 是 pandas 系列,则根据实际值和预测值计算 R^2:
Here's a very simple python function to compute R^2 from the actual and predicted values assuming y and y_hat are pandas series:
R 平方是一种仅适用于线性回归的统计量。
本质上,它测量线性回归可以解释数据中的变化程度。
因此,您计算“总平方和”,即每个结果变量与其平均值的总平方偏差。 。 。
其中 y_bar 是 y 的平均值。
然后,您计算“回归平方和”,即您的 FITTED 值与平均值的差异
并找出两者的比率。
现在,对于多项式拟合,您所要做的就是插入该模型中的 y_hat,但称其为 r 平方并不准确。
这里是我找到的链接这有点说明问题了。
R-squared is a statistic that only applies to linear regression.
Essentially, it measures how much variation in your data can be explained by the linear regression.
So, you calculate the "Total Sum of Squares", which is the total squared deviation of each of your outcome variables from their mean. . .
where y_bar is the mean of the y's.
Then, you calculate the "regression sum of squares", which is how much your FITTED values differ from the mean
and find the ratio of those two.
Now, all you would have to do for a polynomial fit is plug in the y_hat's from that model, but it's not accurate to call that r-squared.
Here is a link I found that speaks to it a little.
维基百科关于 r-squareds 的文章表明它可以用于一般模型拟合而不仅仅是线性回归。
The wikipedia article on r-squareds suggests that it may be used for general model fitting rather than just linear regression.
使用 numpy 模块(在 python3 中测试):
输出:
注:r² ≠ R²
r² 称为“决定系数”
R² 是皮尔逊系数的平方
R²,正式合并为 r²,可能就是您想要的,因为它是最小二乘拟合,这比 r² 的简单分数和更好。 Numpy 不怕称其为“corrcoef”,它假定 Pearson 是事实上的相关系数。
Using the numpy module (tested in python3):
Output:
Note: r² ≠ R²
r² is called the "Coefficient of Determination"
R² is the square of the Pearson Coefficient
R², officially conflated as r², is probably the one you want, as it's a least-square fit, which is better than the simple fraction of sums that r² is. Numpy is not afraid to call it "corrcoef", which presupposes Pearson is the de-facto correlation coefficient.
您可以直接执行此代码,这将为您找到多项式,并为您找到R值如果您需要更多解释,可以在下面发表评论。
You can execute this code directly, this will find you the polynomial, and will find you the R-value you can put a comment down below if you need more explanation.
来自 scipy.stats.linregress 来源。 他们使用平均平方和方法。
From scipy.stats.linregress source. They use the average sum of squares method.
您可以直接在 numpy==1.26 中执行此操作,无需任何额外的库,只需传递
full=True
:np.polyfit(xs, ys, 1, full=True)
示例:
(0.9920000000000001 -0.001999999999999821 array([0.00568] ))
数组([0.99630472])
you can do it directly in numpy==1.26 without any extra libraries by passing
full=True
:np.polyfit(xs, ys, 1, full=True)
Example:
(0.9920000000000001 -0.001999999999999821 array([0.00568]))
array([0.99630472])