Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added docs/source/_static/images/mixed_lm.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 5 additions & 0 deletions docs/source/examples/landing.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@
"text": "Weighted Least Squares",
"target": "notebooks/generated/wls.html",
"img": "../_static/images/wls.png"
},
{
"text": "Linear Mixed-Effects",
"target": "notebooks/generated/mixed_lm_example.html",
"img": "../_static/images/mixed_lm.png"
}
]
},
Expand Down
364 changes: 364 additions & 0 deletions examples/notebooks/mixed_lm_example.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,364 @@
{
"metadata": {
"name": "",
"signature": "sha256:763d9b3eb37822156eb19df1effa86a31b06ec5019ecbd7f0be4a2b160a57229"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Linear Mixed Effects Models"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import numpy as np\n",
"import statsmodels.api as sm\n",
"import statsmodels.formula.api as smf"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%load_ext rpy2.ipython"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%R library(lme4)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Comparing R lmer to Statsmodels MixedLM\n",
"=======================================\n",
"\n",
"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.\n",
"\n",
"Here we show how linear mixed models can be fit using the MixedLM procedure in Statsmodels. Results from R (LME4) are included for comparison. \n",
"\n",
"Here are our import statements:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Growth curves of pigs\n",
"\n",
"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. "
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"data = sm.datasets.get_rdataset('dietox', 'geepack').data\n",
"md = smf.mixedlm(\"Weight ~ Time\", data, groups=data[\"Pig\"])\n",
"mdf = md.fit()\n",
"print(mdf.summary())"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is the same model fit in R using LMER:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%R \n",
"data(dietox, package='geepack')"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%R print(summary(lmer('Weight ~ Time + (1|Pig)', data=dietox)))"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"\n",
"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.\n",
"\n",
"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)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"md = smf.mixedlm(\"Weight ~ Time\", data, groups=data[\"Pig\"], re_formula=\"~Time\")\n",
"mdf = md.fit()\n",
"print(mdf.summary())"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is the same model fit using LMER in R:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%R print(summary(lmer(\"Weight ~ Time + (1 + Time | Pig)\", data=dietox)))"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
".294 / (19.493 * .416)**.5"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"md = smf.mixedlm(\"Weight ~ Time\", data, groups=data[\"Pig\"],\n",
" re_formula=\"~Time\")\n",
"free = sm.regression.mixed_linear_model.MixedLMParams.from_components(np.ones(2), \n",
" np.eye(2))\n",
"\n",
"mdf = md.fit(free=free)\n",
"print(mdf.summary())"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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. \n",
"\n",
"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):"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%R print(summary(lmer(\"Weight ~ Time + (1 | Pig) + (0 + Time | Pig)\", data=dietox)))"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Sitka growth data\n",
"\n",
"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."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"data = sm.datasets.get_rdataset(\"Sitka\", \"MASS\").data\n",
"endog = data[\"size\"]\n",
"data[\"Intercept\"] = 1\n",
"exog = data[[\"Intercept\", \"Time\"]]"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"md = sm.MixedLM(endog, exog, groups=data[\"tree\"], exog_re=exog[\"Intercept\"])\n",
"mdf = md.fit()\n",
"print(mdf.summary())"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is the same model fit in R using LMER:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%%R\n",
"data(Sitka, package=\"MASS\")\n",
"print(summary(lmer(\"size ~ Time + (1 | tree)\", data=Sitka)))"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"%R print(summary(lmer(\"size ~ Time + (1 + Time | tree)\", data=Sitka)))"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"exog_re = exog.copy()\n",
"md = sm.MixedLM(endog, exog, data[\"tree\"], exog_re)\n",
"mdf = md.fit()\n",
"print(mdf.summary())"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can investigate this variance parameter further by constructing a profile likelihood. Some convergence warnings may be generated due to the difficulty of optimizing close to the boundary of the parameter space."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"likev = mdf.profile_re(1, dist_low=0.0001, dist_high=0.01)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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. The profile likelihood plot shows that the MLE of the random slope variance parameter is a very small possitive number, and that there is low uncertainty in this estimate. Note that the log-likeilihood for the model with the variance of the random slope set to zero (as calculated above), is -82, which would appear on this plot as -164. Extrapolating the curve to the left is consistent with this point. It appears that lmer is not fully optimizing the likeihood in this case."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import matplotlib.pyplot as plt"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"plt.figure(figsize=(10,8))\n",
"plt.plot(likev[:,0], 2*likev[:,1])\n",
"plt.xlabel(\"Variance of random slope\", size=17)\n",
"plt.ylabel(\"-2 times profile log likelihood\", size=17)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"likev"
],
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
}
Loading