Linear Mixed Effects Models

Link to Notebook GitHub

In [ ]:
import numpy as np
import statsmodels.api as sm
import statsmodels.formula.api as smf
In [ ]:
%load_ext rpy2.ipython
In [ ]:
%R library(lme4)

Comparing R lmer to Statsmodels MixedLM

The Statsmodels imputation of linear mixed models (MixedLM) closely follows the approach outlined in Lindstrom and Bates (JASA 1988). This is also the approach followed in the R package LME4. Other packages such as Stata, SAS, etc. should also be consistent with this approach, as the basic techniques in this area are mostly mature.

Here we show how linear mixed models can be fit using the MixedLM procedure in Statsmodels. Results from R (LME4) are included for comparison.

Here are our import statements:

Growth curves of pigs

These are longitudinal data from a factorial experiment. The outcome variable is the weight of each pig, and the only predictor variable we will use here is "time". First we fit a model that expresses the mean weight as a linear function of time, with a random intercept for each pig. The model is specified using formulas. Since the random effects structure is not specified, the default random effects structure (a random intercept for each group) is automatically used.

In [ ]:
data = sm.datasets.get_rdataset('dietox', 'geepack').data
md = smf.mixedlm("Weight ~ Time", data, groups=data["Pig"])
mdf = md.fit()
print(mdf.summary())
Error in library(lme4) : there is no package called ‘lme4’

Here is the same model fit in R using LMER:

In [ ]:
%%R
data(dietox, package='geepack')
         Mixed Linear Model Regression Results
========================================================
Model:            MixedLM Dependent Variable: Weight
No. Observations: 861     Method:             REML
No. Groups:       72      Scale:              11.3668
Min. group size:  11      Likelihood:         -2404.7753
Max. group size:  12      Converged:          Yes
Mean group size:  12.0
--------------------------------------------------------
             Coef.  Std.Err.    z    P>|z| [0.025 0.975]
--------------------------------------------------------
Intercept    15.724    0.788  19.952 0.000 14.180 17.269
Time          6.942    0.033 207.939 0.000  6.877  7.008
Intercept RE 40.399    2.166
========================================================

In [ ]:
%R print(summary(lmer('Weight ~ Time + (1|Pig)', data=dietox)))
Error in find.package(package, lib.loc, verbose = verbose) :
  there is no package called ‘geepack’

Note that in the Statsmodels summary of results, the fixed effects and random effects parameter estimates are shown in a single table. The random effect for animal is labeled "Intercept RE" in the Statmodels output above. In the LME4 output, this effect is the pig intercept under the random effects section.

There has been a lot of debate about whether the standard errors for random effect variance and covariance parameters are useful. In LME4, these standard errors are not displayed, because the authors of the package believe they are not very informative. While there is good reason to question their utility, we elected to include the standard errors in the summary table, but do not show the corresponding Wald confidence intervals.

Next we fit a model with two random effects for each animal: a random intercept, and a random slope (with respect to time). This means that each pig may have a different baseline weight, as well as growing at a different rate. The formula specifies that "Time" is a covariate with a random coefficient. By default, formulas always include an intercept (which could be suppressed here using "0 + Time" as the formula).

In [ ]:
md = smf.mixedlm("Weight ~ Time", data, groups=data["Pig"], re_formula="~Time")
mdf = md.fit()
print(mdf.summary())
Error in summary(lmer("Weight ~ Time + (1|Pig)", data = dietox)) :
  could not find function "lmer"

Here is the same model fit using LMER in R:

In [ ]:
%R print(summary(lmer("Weight ~ Time + (1 + Time | Pig)", data=dietox)))
              Mixed Linear Model Regression Results
=================================================================
Model:               MixedLM    Dependent Variable:    Weight
No. Observations:    861        Method:                REML
No. Groups:          72         Scale:                 6.0374
Min. group size:     11         Likelihood:            -2217.0475
Max. group size:     12         Converged:             Yes
Mean group size:     12.0
-----------------------------------------------------------------
                       Coef.  Std.Err.   z    P>|z| [0.025 0.975]
-----------------------------------------------------------------
Intercept              15.739    0.550 28.609 0.000 14.661 16.817
Time                    6.939    0.080 86.927 0.000  6.783  7.095
Intercept RE           19.493    1.572
Intercept RE x Time RE  0.294    0.154
Time RE                 0.416    0.033
=================================================================

The random intercept and random slope are only weakly correlated $(0.294 / \sqrt{19.493 * 0.416} \approx 0.1)$. So next we fit a model in which the two random effects are constrained to be uncorrelated:

In [ ]:
.294 / (19.493 * .416)**.5
Error in summary(lmer("Weight ~ Time + (1 + Time | Pig)", data = dietox)) :
  could not find function "lmer"
In [ ]:
md = smf.mixedlm("Weight ~ Time", data, groups=data["Pig"],
                  re_formula="~Time")
free = sm.regression.mixed_linear_model.MixedLMParams.from_components(np.ones(2),
                                                                      np.eye(2))

mdf = md.fit(free=free)
print(mdf.summary())

The likelihood drops by 0.3 when we fix the correlation parameter to 0. Comparing 2 x 0.3 = 0.6 to the chi^2 1 df reference distribution suggests that the data are very consistent with a model in which this parameter is equal to 0.

Here is the same model fit using LMER in R (note that here R is reporting the REML criterion instead of the likelihood, where the REML criterion is twice the log likeihood):

In [ ]:
%R print(summary(lmer("Weight ~ Time + (1 | Pig) + (0 + Time | Pig)", data=dietox)))
              Mixed Linear Model Regression Results
=================================================================
Model:               MixedLM    Dependent Variable:    Weight
No. Observations:    861        Method:                REML
No. Groups:          72         Scale:                 6.0281
Min. group size:     11         Likelihood:            -2217.3481
Max. group size:     12         Converged:             Yes
Mean group size:     12.0
-----------------------------------------------------------------
                       Coef.  Std.Err.   z    P>|z| [0.025 0.975]
-----------------------------------------------------------------
Intercept              15.740    0.554 28.385 0.000 14.653 16.827
Time                    6.939    0.080 86.248 0.000  6.781  7.097
Intercept RE           19.845    1.584
Intercept RE x Time RE  0.000    0.000
Time RE                 0.423    0.033
=================================================================

Sitka growth data

This is one of the example data sets provided in the LMER R library. The outcome variable is the size of the tree, and the covariate used here is a time value. The data are grouped by tree.

In [ ]:
data = sm.datasets.get_rdataset("Sitka", "MASS").data
endog = data["size"]
data["Intercept"] = 1
exog = data[["Intercept", "Time"]]
Error in summary(lmer("Weight ~ Time + (1 | Pig) + (0 + Time | Pig)",  :
  could not find function "lmer"

Here is the statsmodels LME fit for a basic model with a random intercept. We are passing the endog and exog data directly to the LME init function as arrays. Also note that endog_re is specified explicitly in argument 4 as a random intercept (although this would also be the default if it were not specified).

In [ ]:
md = sm.MixedLM(endog, exog, groups=data["tree"], exog_re=exog["Intercept"])
mdf = md.fit()
print(mdf.summary())

Here is the same model fit in R using LMER:

In [ ]:
%%R
data(Sitka, package="MASS")
print(summary(lmer("size ~ Time + (1 | tree)", data=Sitka)))
        Mixed Linear Model Regression Results
======================================================
Model:            MixedLM Dependent Variable: size
No. Observations: 395     Method:             REML
No. Groups:       79      Scale:              0.0392
Min. group size:  5       Likelihood:         -82.3884
Max. group size:  5       Converged:          Yes
Mean group size:  5.0
------------------------------------------------------
             Coef. Std.Err.   z    P>|z| [0.025 0.975]
------------------------------------------------------
Intercept    2.273    0.088 25.863 0.000  2.101  2.446
Time         0.013    0.000 47.796 0.000  0.012  0.013
Intercept RE 0.375    0.348
======================================================

We can now try to add a random slope. We start with R this time. From the code and output below we see that the REML estimate of the variance of the random slope is nearly zero.

In [ ]:
%R print(summary(lmer("size ~ Time + (1 + Time | tree)", data=Sitka)))
Error in summary(lmer("size ~ Time + (1 | tree)", data = Sitka)) :
  could not find function "lmer"

If we run this in statsmodels LME with defaults, we see that the variance estimate is indeed very small, which leads to a warning about the solution being on the boundary of the parameter space. The regression slopes agree very well with R, but the likelihood value is much higher than that returned by R.

In [ ]:
exog_re = exog.copy()
md = sm.MixedLM(endog, exog, data["tree"], exog_re)
mdf = md.fit()
print(mdf.summary())
Error in summary(lmer("size ~ Time + (1 + Time | tree)", data = Sitka)) :
  could not find function "lmer"

We can further explore the random effects struture by constructing plots of the profile likelihoods. We start with the random intercept, generating a plot of the profile likelihood from 0.1 units below to 0.1 units above the MLE. Since each optimization inside the profile likelihood generates a warning (due to the random slope variance being close to zero), we turn off the warnings here.

In [ ]:
import warnings

with warnings.catch_warnings():
    warnings.filterwarnings("ignore")
    likev = mdf.profile_re(0, dist_low=0.1, dist_high=0.1)
              Mixed Linear Model Regression Results
=================================================================
Model:                 MixedLM    Dependent Variable:    size
No. Observations:      395        Method:                REML
No. Groups:            79         Scale:                 0.0264
Min. group size:       5          Likelihood:            -62.4834
Max. group size:       5          Converged:             Yes
Mean group size:       5.0
-----------------------------------------------------------------
                       Coef.  Std.Err.   z    P>|z| [0.025 0.975]
-----------------------------------------------------------------
Intercept               2.273    0.101 22.513 0.000  2.075  2.471
Time                    0.013    0.000 33.888 0.000  0.012  0.013
Intercept RE            0.646    0.923
Intercept RE x Time RE -0.001    0.003
Time RE                 0.000    0.000
=================================================================

/Users/tom.augspurger/Envs/py3/lib/python3.4/site-packages/statsmodels-0.6.1-py3.4-macosx-10.10-x86_64.egg/statsmodels/regression/mixed_linear_model.py:1717: ConvergenceWarning: The MLE may be on the boundary of the parameter space.
  warnings.warn(msg, ConvergenceWarning)

Here is a plot of the profile likelihood function. We multiply the log-likelihood difference by 2 to obtain the usual $\chi^2$ reference distribution with 1 degree of freedom.

In [ ]:
import matplotlib.pyplot as plt
In [ ]:
plt.figure(figsize=(10,8))
plt.plot(likev[:,0], 2*likev[:,1])
plt.xlabel("Variance of random slope", size=17)
plt.ylabel("-2 times profile log likelihood", size=17)

Here is a plot of the profile likelihood function. The profile likelihood plot shows that the MLE of the random slope variance parameter is a very small positive number, and that there is low uncertainty in this estimate.

In [ ]:
re = mdf.cov_re.iloc[1, 1]
likev = mdf.profile_re(1, dist_low=.5*re, dist_high=0.8*re)

plt.figure(figsize=(10, 8))
plt.plot(likev[:,0], 2*likev[:,1])
plt.xlabel("Variance of random slope", size=17)
plt.ylabel("-2 times profile log likelihood", size=17)