scipy.stats.

linregress#

scipy.stats.linregress(x, y=None, alternative='two-sided')[source]#

計算兩組測量值的線性最小平方法迴歸。

參數:
x, yarray_like

兩組測量值。兩個陣列應具有相同的長度 N。如果僅給定 x (且 y=None),則它必須是二維陣列,其中一個維度的長度為 2。然後通過沿長度為 2 的維度分割陣列來找到兩組測量值。在 y=Nonex 是 2xN 陣列的情況下,linregress(x) 等效於 linregress(x[0], x[1])

Deprecated since version 1.14.0: 從單個參數 x 推斷兩組測量值已被棄用,將在 SciPy 1.16.0 中導致錯誤;這些集合必須作為 xy 單獨指定。

alternative{‘two-sided’, ‘less’, ‘greater’}, optional

定義對立假設。預設值為 ‘two-sided’。以下選項可用

  • ‘two-sided’: 迴歸線的斜率不為零

  • ‘less’: 迴歸線的斜率小於零

  • ‘greater’: 迴歸線的斜率大於零

Added in version 1.7.0.

返回:
resultLinregressResult 實例

傳回值是一個具有以下屬性的物件

slopefloat

迴歸線的斜率。

interceptfloat

迴歸線的截距。

rvaluefloat

皮爾森相關係數。rvalue 的平方等於判定係數。

pvaluefloat

假設檢定的 p 值,其虛無假設是斜率為零,使用 Wald 檢定和檢定統計量的 t 分佈。有關對立假設,請參閱上面的 alternative

stderrfloat

估計斜率(梯度)的標準誤差,假設殘差常態性。

intercept_stderrfloat

估計截距的標準誤差,假設殘差常態性。

另請參閱

scipy.optimize.curve_fit

使用非線性最小平方法將函數擬合到資料。

scipy.optimize.leastsq

最小化一組方程式的平方和。

註解

為了與舊版本的 SciPy 相容,傳回值的行為類似於長度為 5 的 namedtuple,其欄位為 slopeinterceptrvaluepvaluestderr,因此可以繼續寫入

slope, intercept, r, p, se = linregress(x, y)

使用該樣式,截距的標準誤差不可用。若要存取所有計算值,包括截距的標準誤差,請將傳回值用作具有屬性的物件,例如:

result = linregress(x, y)
print(result.intercept, result.intercept_stderr)

範例

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from scipy import stats
>>> rng = np.random.default_rng()

產生一些資料

>>> x = rng.random(10)
>>> y = 1.6*x + rng.random(10)

執行線性迴歸

>>> res = stats.linregress(x, y)

判定係數 (R 平方)

>>> print(f"R-squared: {res.rvalue**2:.6f}")
R-squared: 0.717533

繪製資料以及擬合線

>>> plt.plot(x, y, 'o', label='original data')
>>> plt.plot(x, res.intercept + res.slope*x, 'r', label='fitted line')
>>> plt.legend()
>>> plt.show()
../../_images/scipy-stats-linregress-1_00_00.png

計算斜率和截距的 95% 信賴區間

>>> # Two-sided inverse Students t-distribution
>>> # p - probability, df - degrees of freedom
>>> from scipy.stats import t
>>> tinv = lambda p, df: abs(t.ppf(p/2, df))
>>> ts = tinv(0.05, len(x)-2)
>>> print(f"slope (95%): {res.slope:.6f} +/- {ts*res.stderr:.6f}")
slope (95%): 1.453392 +/- 0.743465
>>> print(f"intercept (95%): {res.intercept:.6f}"
...       f" +/- {ts*res.intercept_stderr:.6f}")
intercept (95%): 0.616950 +/- 0.544475