使用statsmodel.formula.api与statsmodel.api进行OLS [英] OLS using statsmodel.formula.api versus statsmodel.api

查看:2983
本文介绍了使用statsmodel.formula.api与statsmodel.api进行OLS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释statsmodel.formula.api中的ols与statsmodel.api中的ols之间的区别吗?

Can anyone explain to me the difference between ols in statsmodel.formula.api versus ols in statsmodel.api?

使用ISLR文本中的广告数据,我同时使用了两者,并获得了不同的结果.然后,我将其与scikit-learn的LinearRegression进行了比较.

Using the Advertising data from the ISLR text, I ran an ols using both, and got different results. I then compared with scikit-learn's LinearRegression.

import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
import statsmodels.api as sm
from sklearn.linear_model import LinearRegression

df = pd.read_csv("C:\...\Advertising.csv")

x1 = df.loc[:,['TV']]
y1 = df.loc[:,['Sales']]

print "Statsmodel.Formula.Api Method"
model1 = smf.ols(formula='Sales ~ TV', data=df).fit()
print model1.params

print "\nStatsmodel.Api Method"
model2 = sm.OLS(y1, x1)
results = model2.fit()
print results.params

print "\nSci-Kit Learn Method"
model3 = LinearRegression()
model3.fit(x1, y1)
print model3.coef_
print model3.intercept_

输出如下:

Statsmodel.Formula.Api Method
Intercept    7.032594
TV           0.047537
dtype: float64

Statsmodel.Api Method
TV    0.08325
dtype: float64

Sci-Kit Learn Method
[[ 0.04753664]]
[ 7.03259355]

statsmodel.api方法返回的电视参数与statsmodel.formula.api和scikit-learn方法不同.

The statsmodel.api method returns a different parameter for TV from the statsmodel.formula.api and the scikit-learn methods.

运行statsmodel.api会产生不同结果的哪种ols算法?是否有人链接到可以帮助回答此问题的文档?

What kind of ols algorithm is statsmodel.api running that would produce a different result? Does anyone have a link to documentation that could help answer this question?

推荐答案

区别在于是否存在拦截:

The difference is due to the presence of intercept or not:

  • statsmodels.formula.api中,与R方法类似,常量会自动添加到您的数据中,并且截距会被拟合
  • statsmodels.api中的
  • 中,您必须自己添加一个常量(请参见 add_constant /p>

  • in statsmodels.formula.api, similarly to the R approach, a constant is automatically added to your data and an intercept in fitted
  • in statsmodels.api, you have to add a constant yourself (see the documentation here). Try using add_constant from statsmodels.api

x1 = sm.add_constant(x1)

这篇关于使用statsmodel.formula.api与statsmodel.api进行OLS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆