scipy.stats. linegress-获取截距的p值

ars1skjm  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(232)

scipy.stats.linregress返回与斜率对应的p值,但不返回截距的p值。请考虑文档中的以下示例:

>>> from scipy import stats
>>> import numpy as np
>>> x = np.random.random(10)
>>> y = np.random.random(10)
>>> slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
>>> p_value
0.40795314163864016

根据文件,p-value是“零假设为斜率为零的假设检验的双侧p值”。我想得到相同的统计量,但是截距而不是斜率。
statsmodels.regression.linear_model.OLS会立即传回两个系数的p值:

>>> import numpy as np

>>> import statsmodels.api as sm

>>> X = sm.add_constant(x)
>>> model = sm.OLS(y,X)
>>> results = model.fit()
>>> results.pvalues
array([ 0.00297559,  0.40795314])

仅使用scipy,如何获得截距的p值(0.40795314163864016)?

70gysomp

70gysomp1#

要计算截距的p值,请执行以下操作:

  • 从tvalue开始,tvalue是从截距的平均值和标准偏差开始计算的(参见下面的函数tvalue
  • 然后使用t分布的生存函数和自由度计算p值(参见下面的函数pvalue

scipy案例的Python代码:

import scipy.stats
from scipy import stats
import numpy as np

def tvalue(mean, stderr):
    return mean / stderr

def pvalue(tvalue, dof):
    return 2*scipy.stats.t.sf(abs(tvalue), dof)

np.random.seed(42)
x = np.random.random(10)
y = np.random.random(10)
scipy_results = stats.linregress(x,y)
print(scipy_results)
dof = 1.0*len(x) - 2
print("degrees of freedom = ", dof)
tvalue_intercept = tvalue(scipy_results.intercept, scipy_results.intercept_stderr)
tvalue_slope = tvalue(scipy_results.slope, scipy_results.stderr)
pvalue_intercept = pvalue(tvalue_intercept, dof)
pvalue_slope = pvalue(tvalue_slope, dof)
print(f"""tvalues(intercept, slope) = {tvalue_intercept, tvalue_slope}
pvalues(intercept, slope) = {pvalue_intercept, pvalue_slope}
""")

输出:

LinregressResult(slope=0.6741948478345656, intercept=0.044594333294114996, rvalue=0.7042846127289285, pvalue=0.02298486740535295, stderr=0.24027039310814322, intercept_stderr=0.14422953722007206)
degrees of freedom =  8.0
tvalues(intercept, slope) = (0.30919001858870915, 2.8059838713924172)
pvalues(intercept, slope) = (0.7650763497698203, 0.02298486740535295)

与使用statsmodels获得的结果进行比较:

import statsmodels.api as sm
import math

X = sm.add_constant(x)
model = sm.OLS(y,X)
statsmodels_results = model.fit()
print(f"""intercept, slope = {statsmodels_results.params}
rvalue = {math.sqrt(statsmodels_results.rsquared)}
tvalues(intercept, slope) = {statsmodels_results.tvalues}
pvalues(intercept, slope) = {statsmodels_results.pvalues}""")

输出:

intercept, slope = [0.04459433 0.67419485]
rvalue = 0.7042846127289285
tvalues(intercept, slope) = [0.30919002 2.80598387]
pvalues(intercept, slope) = [0.76507635 0.02298487]

条注解

  • 固定随机种子以具有可再现的结果
  • 使用也包含intercept_stderrLinregressResult对象

参考文献

unhi4e5o

unhi4e5o2#

来自SciPy.org的文档:https://docs.scipy.org/doc/scipy-.14.0/reference/generated/scipy.stats.linregress.html

print "r-squared:", r_value**2

输出功率
相关系数平方:0.15286643777
对于其他参数,请尝试:

print ('Intercept is: ', (intercept))
print ('Slope is: ', (slope))
print ('R-Value is: ', (r_value))
print ('Std Error is: ', (std_err))
print ('p-value is: ', (p_value))

相关问题