stats.linregress 中的 r 与 statsmodels 中的 r 平方比较 [英] r in stats.linregress compared to r-squared in statsmodels
问题描述
我正在开发一个程序来研究一些类星体的震级和红移之间的相关性,我正在使用 statsmodels
和 scipy.stats.linregress
来计算数据统计;statsmodels
计算 r-squared
(以及其他参数),以及 stats.linregress
计算 r
(以及其他参数)).
I'm working on a program to investigate the correlation between magnitude and redshift for some quasars, and I'm using statsmodels
and scipy.stats.linregress
to compute the statistics of the data; statsmodels
to compute r-squared
(among other parameters), and stats.linregress
to compute r
(among others).
一些示例输出是:
W1 r-squared: 0.855715
W1 r-value : 0.414026
W2 r-squared: 0.861169
W2 r-value : 0.517381
W3 r-squared: 0.874051
W3 r-value : 0.418523
W4 r-squared: 0.856747
W4 r-value : 0.294094
Visual minus WISE r-squared: 0.87366
Visual minus WISE r-value : -0.521463
我的问题是,为什么 r
和 r-squared
值不匹配
My question is, why do the r
and r-squared
values not match
(即对于 W1 波段,0.414026**2 != 0.855715)?
(i.e. for the W1 band, 0.414026**2 != 0.855715)?
我的计算函数代码如下:
The code for my computation function is as follows:
def computeStats(x, y, yName):
from scipy import stats
import statsmodels.api as sm
# Compute model parameters
model = sm.OLS(y, x, missing= 'drop')
results = model.fit()
# Mask NaN values in both axes
mask = ~np.isnan(y) & ~np.isnan(x)
# Compute fit parameters
params = stats.linregress(x[mask], y[mask])
fit = params[0]*x + params[1]
fitEquation = '$(%s)=(%.4g \pm %.4g) \\times redshift+%.4g$'%(yName,
params[0], # slope
params[4], # stderr in slope
params[1]) # y-intercept
print('%s r-squared: %g'%(name, arrayresults.rsquared))
print('%s r-value : %g'%(name, arrayparams[2]))
return results, params, fit, fitEquation
我是否错误地解释了统计数据?还是这两个模块使用不同的方法计算回归?
Am I interpreting the statistics incorrectly? Or do the two modules compute the regressions using different methods?
推荐答案
默认情况下,statsmodels
中的 OLS
不包括常数项(即截距)线性方程.(常数项对应于设计矩阵中的一列.)
By default, OLS
in statsmodels
does not include the constant term (i.e. the intercept) in the linear equation. (The constant term corresponds to a column of ones in the design matrix.)
要匹配linregress
,像这样创建model
:
model = sm.OLS(y, sm.add_constant(x), missing= 'drop')
这篇关于stats.linregress 中的 r 与 statsmodels 中的 r 平方比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!