为什么我只从statsmodels OLS中获得一个参数

时间:2013-12-20 10:27:11

标签: python pandas linear-regression statsmodels

这是我正在做的事情:

$ 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])

我原本期望有两个元素的数组?!? 截距和斜率系数?

5 个答案:

答案 0 :(得分:41)

试试这个:

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

documentation

一样
  

默认情况下不包括拦截,应由用户添加

statsmodels.tools.tools.add_constant

答案 1 :(得分:6)

为了完成,这有效:

>>> 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])

它确实给了我一个不同的斜率系数,但我想我们现在的数字有一个截距。

答案 2 :(得分:1)

我正在运行0.6.1,看起来“add_constant”函数已被移入statsmodels.tools模块。这是我运行的工作:

#include <stdio.h>

int wordlength();

int main() {

printf("%d", wordlength()); // prints 4195424 but
                          // if I uncomment the code below
                          // it then prints 32 like I want

//  int count;
//  unsigned int n = ~0;
// 
//  while( n != 0) {
//      n = n >> 1;
//      count++;
//  }
//  printf("\n%d", count); // prints 32 as expected

    return 0;
}

int wordlength() {

    int count;
    unsigned int n = ~0;

    while( n != 0) {
        n = n >> 1;
        count++;
    }

    return count;
}

答案 3 :(得分:1)

尝试一下,它对我有用:

import statsmodels.formula.api as sm

from statsmodels.api import add_constant

X_train = add_constant(X_train)

X_test = add_constant(X_test)


model = sm.OLS(y_train,X_train)

results = model.fit()

y_pred=results.predict(X_test)

results.params

答案 4 :(得分:0)

我确实添加了代码X = sm.add_constant(X),但是python没有返回拦截值,因此我决定使用一些代数自己在代码中完成此操作:

此代码计算了35个样本,7个特征以及我作为等式添加为特征的一个截距值的回归:

import statsmodels.api as sm
from sklearn import datasets ## imports datasets from scikit-learn
import numpy as np
import pandas as pd

x=np.empty((35,8)) # (numSamples, oneIntercept + numFeatures))
feature_names = np.empty((8,))
y = np.empty((35,))

dbfv = open("dataset.csv").readlines()


interceptConstant = 1;
i = 0
# reading data and writing in numpy arrays
while i<len(dbfv):
    cells = dbfv[i].split(",")
    j = 0
    x[i][j] = interceptConstant
    feature_names[j] = str(j)
    while j<len(cells)-1:
        x[i][j+1] = cells[j]
        feature_names[j+1] = str(j+1)
        j += 1
    y[i] = cells[len(cells)-1]
    i += 1
# creating dataframes
df = pd.DataFrame(x, columns=feature_names)

target = pd.DataFrame(y, columns=["TARGET"])

X = df
y = target["TARGET"]

model = sm.OLS(y, X).fit()

print(model.params)

# predictions = model.predict(X) # make the predictions by the model


# Print out the statistics
print(model.summary())