Get random effect intercept value for every level in statsmodels - python

I'm going through a tutorial on mixed-effects models in Python.
I'm building a model where litter is the random effect. In the tutorial, the output contains the variance across the litter intercepts. However, in Bayesian hierarchical modeling, I'm also able to see the intercepts for every level of the random effect variable.
How would I see that here?
import pandas as pd
import statsmodels.api as sm
import scipy.stats as stats
import statsmodels.formula.api as smf
df = pd.read_csv("http://www-personal.umich.edu/~bwest/rat_pup.dat", sep = "\t")
model = smf.mixedlm("weight ~ litsize + C(treatment) + C(sex, Treatment('Male')) + C(treatment):C(sex, Treatment('Male'))",
df,
groups= "litter").fit()
model.summary()
I would also ideally like to see the estimate of the intercept across all litters. Then, how would I interpret that overall intercept compared to the intercept for each single litter?
If there's a better Python package for what I'm striving for, please suggest.

Related

Scikit learn does not appear to respect global / local random_states in unittests

I'm trying to write an integration test that uses the descriptive statistics (.describe().to_list()) of the results of a model prediction (model.predict(X)). However, even though I've set np.random.seed(###) the descriptive statistics are different after running the tests in the console vs. in the environment created by Pycharm:
Here's a MRE for local:
from sklearn.linear_model import ElasticNet
from sklearn.datasets import make_regression
import numpy as np
import pandas as pd
np.random.seed(42)
X, y = make_regression(n_features=2, random_state=42)
regr = ElasticNet(random_state=42)
regr.fit(X, y)
pred = regr.predict(X)
# Theory: This result should be the same from the result in a class
pd.Series(pred).describe().to_list()
And an example test-file:
from unittest import TestCase
from sklearn.linear_model import ElasticNet
from sklearn.datasets import make_regression
import numpy as np
import pandas as pd
np.random.seed(42)
class TestPD(TestCase):
def testExpectedPrediction(self):
np.random.seed(42)
X, y = make_regression(n_features=2, random_state=42)
regr = ElasticNet(random_state=42)
regr.fit(X, y)
pred = pd.Series(regr.predict(X))
for i in pred.describe().to_list():
print(i)
# here we would have a self.assertTrue/Equals f.e. element
What appears to happen is that when I run this test in the Python Console, I get one result. But then when I run it using PyCharm's unittests for the folder, I get another result. Now, importantly, in PyCharm, the project interpreter is used to create an environment for the console that ought to be the same as the test environment. This leaves me to believe that I'm missing something about the way random_state is passed along. My expectation is, given that I have set a seed, that the results would be reproducible. But that doesn't appear to be the case and I would like to understand:
Why they aren't equal?
What I can do to make them equal?
I haven't been able to find a lot of best practices with respect to testing against expected model results. So commentary in that regard would also be helpful.

Linear Regression in Python: Scipy vs. Statsmodels - same R², different coefficients

I'm running linear regressions with statsmodels and because I tend to distrust my results I also ran the same regression with scipy. The underlying dataset has about 80,000 observations. Unofrtunately, I cannot provide the data for you to reproduce the errors.
I run two rounds of regressions: first simple OLS, second simple OLS with standardized variables
Surprisingly, the results differ a lot. While R² and p-value seem to be the same, coefficients, intercept and standard error are all over the place. Interestingly, after standardizing the results align more. Now, there is only a slight difference in the constant, which I am happy to attribute to rounding issues.
The exact numbers can be found in the appended screenshots.
Any idea, where these differences come from and why they disappear after standardizing? What did I do wrong? Do I have to be extra worried, since I run most of my regressions with sklearn (only swapped to statsmodels since I needed some p-values) and even more differences may occur?
Thanks for your help! If you need any additional information, feel free to ask. Code and Screenshots are povided below.
My code in short looks like this:
# package import
import numpy as np
from scipy.stats import linregress
from scipy.stats.mstats import zscore
import statsmodels.api as sma
import statsmodels.formula.api as smf
# adding constant
train_IV_cons = sma.add_constant(train_IV)
# run regression
(coefficients, intercept, rvalue, pvalue, stderr) = linregress(train_IV[:,0], train_DV)
print(coefficients, intercept, rvalue, pvalue, stderr)
est = smf.OLS(train_DV, train_IV_cons[:,[0,1]])
model_results = est.fit()
print(model_results.summary())
# normalize variables
train_IV_norm = train_IV
train_IV_norm[:,0]=np.array(ss.zscore(train_IV_norm[:,0]))
train_IV_norm_cons = sma.add_constant(train_IV_norm)
# run regressions
(coefficients, intercept, rvalue, pvalue, stderr) = linregress(train_IV_norm[:,0], train_DV_norm)
print(coefficients, intercept, rvalue, pvalue, stderr)
est = smf.OLS(train_DV_norm, train_IV_norm_cons[:,[0,1]])
model_results = est.fit()
print(model_results.summary())
First regression (not standardized data):
Second regression (standardized data):

Create file OLS in Python Statsmodels

I dont have much knowledge in Python but I have to crack this for an assessment completion,
Question:
Run the following code to load the required libraries and create the data set to fit the model.
from sklearn.datasets import load_boston
import pandas as pd
boston = load_boston()
dataset = pd.DataFrame(boston.data, columns=boston.feature_names)
dataset['target'] = boston.target
print(dataset.head())
I have to perform the following steps to complete this scenario.
For the boston dataset loaded in the above code snippet, perform linear regression.
Use the target variable as the dependent variable.
Use the RM variable as the independent variable.
Fit a single linear regression model using statsmodels package in python.
Import statsmodels packages appropriately in your code.
Upon fitting the model, Identify the coefficients.
Finally print the model summary in your code.
You can write your code using vim app.py .
Press i for insert mode.
Press esc and then :wq to save and quit the editor.
Please help me to understand how to get this completed. Your valuable comments are much appreciated
Thanks in Advance
from sklearn.datasets import load_boston
import pandas as pd
boston = load_boston()
dataset = pd.DataFrame(boston.data, columns=boston.feature_names)
dataset['target'] = boston.target
print(dataset.head())
import statsmodels.api as sm
import statsmodels.formula.api as smf
X = dataset["RM"]
y = dataset['target']
X = sm.add_constant(X)
model = smf.OLS(y,X).fit()
predictions = model.predict(X)
print(model.summary())

statsmodel: panel regression

I am currently using from pandas.stats.plm import PanelOLS to run Panel regressions. I am needing to switch to statsmodel so that I can ouput heteroskedastic robust results. I have been unable to find notation on calling a panel regression for statsmodel. In general, I find the documentation for statsmodel not very user friendly. Is someone familiar with panel regression syntax in statsmodel?
The linearmodels package is created to extend the statsmodels package to panelOLS (see https://github.com/bashtage/linearmodels). Here is the example from the package doc:
import numpy as np
from statsmodels.datasets import grunfeld
data = grunfeld.load_pandas().data
data.year = data.year.astype(np.int64)
# MultiIndex, entity - time
data = data.set_index(['firm','year'])
from linearmodels import PanelOLS
mod = PanelOLS(data.invest, data[['value','capital']], entity_effect=True)
res = mod.fit(cov_type='clustered', cluster_entity=True)
Best Daniel

How to silence statsmodels.fit() in python

When I want to fit some model in python,
I often use fit() method in statsmodels.
And some cases I write a script for automating fitting:
import statsmodels.formula.api as smf
import pandas as pd
df = pd.read_csv('mydata.csv') # contains column x and y
fitted = smf.poisson('y ~ x', df).fit()
My question is how to silence the fit() method.
In my environment it outputs some information about fitting to standard output like:
Optimization terminated successfully.
Current function value: 2.397867
Iterations 11
but I don't need it.
I couldn't find the argument which controls standard output printing.
How can I silence fit() method?
Python 3.3.4, IPython 2.0.0, pandas 0.13.1, statsmodels 0.5.0.
Use the disp argument to fit. It controls the verbosity of the optimizers in scipy.
mod.fit(disp=0)
See the documentation for fit.

Categories