How to get the regression intercept using Statsmodels.api

Shank picture Shank · Aug 8, 2016 · Viewed 24.8k times · Source

I am trying calculate a regression output using python library but I am unabl;e to get the intercept value when I use the library:

import statsmodels.api as sm

It prints all the regression analysis except the intercept.

but when I use:

from pandas.stats.api import ols

My code for pandas:

Regression = ols(y= Sorted_Data3['net_realization_rate'],x = Sorted_Data3[['Cohort_2','Cohort_3']])
print Regression  

I get the the intercept with a warning that this librabry will be deprecated in the future so I am trying to use Statsmodels.

the warning that I get while using pandas.stats.api:

Warning (from warnings module): File "C:\Python27\lib\idlelib\run.py", line 325 exec code in self.locals FutureWarning: The pandas.stats.ols module is deprecated and will be removed in a future version. We refer to external packages like statsmodels, see some examples here: http://statsmodels.sourceforge.net/stable/regression.html

My code for Statsmodels:

import pandas as pd
import numpy as np
from pandas.stats.api import ols
import statsmodels.api as sm

Data1 = pd.read_csv('C:\Shank\Regression.csv')  #Importing CSV
print Data1

running some cleaning code

sm_model = sm.OLS(Sorted_Data3['net_realization_rate'],Sorted_Data3[['Cohort_2','Cohort_3']])
results = sm_model.fit()
print '\n'
print results.summary()

I even tried statsmodels.formula.api: as:

sm_model = sm.OLS(formula ="net_realization_rate ~ Cohort_2 + Cohort_3", data = Sorted_Data3)
results = sm_model.fit()
print '\n'
print result.params
print '\n'
print results.summary()

but I get the error:

TypeError: init() takes at least 2 arguments (1 given)

Final output: 1st is from pandas 2nd is from Stats.... I want the intercept vaule as the one from pandas from stats also: enter image description here

Answer

Kartik picture Kartik · Aug 8, 2016

So, statsmodels has a add_constant method that you need to use to explicitly add intercept values. IMHO, this is better than the R alternative where the intercept is added by default.

In your case, you need to do this:

import statsmodels.api as sm
endog = Sorted_Data3['net_realization_rate']
exog = sm.add_constant(Sorted_Data3[['Cohort_2','Cohort_3']])

# Fit and summarize OLS model
mod = sm.OLS(endog, exog)
results = mod.fit()
print results.summary()

Note that you can add a constant before your array, or after it by passing True (default) or False to the prepend kwag in sm.add_constant


Or, not recommended, but you can use Numpy to explicitly add a constant column like so:

exog = np.concatenate((np.repeat(1, len(Sorted_Data3))[:, None], 
                       Sorted_Data3[['Cohort_2','Cohort_3']].values),
                       axis = 1)