2013-12-20 186 views
17

下面是我在做什麼:爲什麼我從statsmodels OLS只得到一個參數擬合

$ python 
Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin 
>>> import statsmodels.api as sm 
>>> statsmodels.__version__ 
'0.5.0' 
>>> import numpy 
>>> y = numpy.array([1,2,3,4,5,6,7,8,9]) 
>>> X = numpy.array([1,1,2,2,3,3,4,4,5]) 
>>> res_ols = sm.OLS(y, X).fit() 
>>> res_ols.params 
array([ 1.82352941]) 

我預想的有兩個元素的數組?!? 截距和斜率係數?

+1

[文件](http://statsmodels.sourceforge.net/devel/generated/statsmodels.regression.linear_model.OLS.html):一個interecept不包括默認和應該由用戶添加。請參閱statsmodels.tools.add_constant。 – alko

+2

add_constant()在這裏有什麼意義。當我在線性區域中生成一個模型時,我期望得到一個截距y = mX + C。有人希望有人在輸入向量上添加常數的附加操作。 – Abhi

回答

29

試試這個:

X = sm.add_constant(X) 
sm.OLS(y,X) 

documentations

的interecept默認情況下不包括在內,應該由用戶

statsmodels.tools.tools.add_constant

+0

哇,這很快;-) 謝謝,這有幫助。 – Tom

+0

我在看ols實例[wls頁](http://statsmodels.sourceforge.net/stable/examples/generated/example_wls.html),所以我想這就是爲什麼我忽略了add_constant(),因爲它是沒有在該頁面上提到。 – Tom

+0

@ behzad-nouri,我將不勝感激,如果你可以看看這個:https://stackoverflow.com/questions/44747203/python-ols-regression-and-backward-prediction –

4

加入爲了完成這項工作s:

>>> import numpy 
>>> import statsmodels.api as sm 
>>> y = numpy.array([1,2,3,4,5,6,7,8,9]) 
>>> X = numpy.array([1,1,2,2,3,3,4,4,5]) 
>>> X = sm.add_constant(X) 
>>> res_ols = sm.OLS(y, X).fit() 
>>> res_ols.params 
array([-0.35714286, 1.92857143]) 

它確實給了我一個不同的斜率係數,但我想現在我們已經有一個截距了。

0

我正在運行0.6.1,它看起來像「add_constant」函數已被移入statsmodels.tools模塊。這是我跑了工作:

res_ols = sm.OLS(y, statsmodels.tools.add_constant(X)).fit() 
相關問題