为什么我只能从 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])

我曾期望一个包含两个元素的数组?!?截距和斜率系数?

stack overflow Why do I get only one parameter from a statsmodels OLS fit
原文答案
author avatar

接受的答案

尝试这个:

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

documentation

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

statsmodels.tools.tools.add_constant


答案:

作者头像

只是为了完成,这起作用:

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

它确实给了我不同的坡度系数,但是我想这是我们现在确实有拦截的数字。

作者头像

试试这个,它对我有用:

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
作者头像

我正在运行 0.6.1,看起来“add_constant”函数已移至 statsmodels.tools 模块中。这是我运行的有效方法:

res_ols = sm.OLS(y, statsmodels.tools.add_constant(X)).fit()
作者头像

我确实添加了代码 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())
作者头像

尝试这个

X = sm.add_constant(X)
ols= sm.OLS(y,X)
res_ols= ols.fit()
res_ols.params
res_ols.params[0]
res_ols.params[1]
print(res_ols.summary())