Repository navigation
Description
Hi there,
The formula interface for MixedLM does not know how to handle missing values. It also does not handle categorical data very well, too.
Minimal Example
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
from patsy import dmatrix
from patsy import dmatrices
import statsmodels.api as sm
import statsmodels.formula.api as smf
x = Series(random.randint(0,2,50), dtype='category')
x.cat.categories = ['foo', 'bar']
y = Series(random.randint(0,3,50), dtype='category')
y.cat.categories = ['low', 'medium', 'high']
z = Series(random.randint(0,2,50), dtype='category')
z.cat.categories = ['male', 'female']
data = DataFrame({
'response': random.rand(50),
'assistant': x,
'risk' : y,
'sex': z,
'age': random.randint(20,60,50)})
Which gives us:
In [59]: data.head()
Out[59]:
age assistant response risk sex
0 38 foo 0.524707 medium female
1 38 foo 0.902656 high female
2 39 foo 0.934783 low male
3 53 foo 0.136764 high male
4 34 foo 0.013332 low male
The grouping in the data frame is a categorical value, which mixedlm complains about.
In [65]: fit = smf.mixedlm('response ~ sex + age + risk', groups=data['assistant'], data=data).fit()
/home/moebius/software/python-environments/for/lib/python3.5/site-packages/statsmodels/regression/mixed_linear_model.py:160: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
self._params = np.zeros(self.k_tot)
/home/moebius/software/python-environments/for/lib/python3.5/site-packages/statsmodels/regression/mixed_linear_model.py:1717: ConvergenceWarning: The MLE may be on the boundary of the parameter space.
warnings.warn(msg, ConvergenceWarning)
If we set some covariates to missing, we get an error.
In [66]: data.risk[10] = np.nan
In [67]: fit = smf.mixedlm('response ~ sex + age + risk', groups=data['assistant'], data=data).fit()
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-67-decde0c23284> in <module>()
----> 1 fit = smf.mixedlm('response ~ sex + age + risk', groups=data['assistant'], data=data).fit()
/home/moebius/software/python-environments/for/lib/python3.5/site-packages/statsmodels/regression/mixed_linear_model.py in from_formula(cls, formula, data, re_formula, subset, *args, **kwargs)
651 subset=None,
652 exog_re=exog_re,
--> 653 *args, **kwargs)
654
655 # expand re names to account for pairs of RE
/home/moebius/software/python-environments/for/lib/python3.5/site-packages/statsmodels/base/model.py in from_formula(cls, formula, data, subset, *args, **kwargs)
148 kwargs.update({'missing_idx': missing_idx,
149 'missing': missing})
--> 150 mod = cls(endog, exog, *args, **kwargs)
151 mod.formula = formula
152
/home/moebius/software/python-environments/for/lib/python3.5/site-packages/statsmodels/regression/mixed_linear_model.py in __init__(self, endog, exog, groups, exog_re, use_sqrt, missing, **kwargs)
537
538 # Split the data by groups
--> 539 self.endog_li = self.group_list(self.endog)
540 self.exog_li = self.group_list(self.exog)
541 self.exog_re_li = self.group_list(self.exog_re)
/home/moebius/software/python-environments/for/lib/python3.5/site-packages/statsmodels/regression/mixed_linear_model.py in group_list(self, array)
671 if array.ndim == 1:
672 return [np.array(array[self.row_indices[k]])
--> 673 for k in self.group_labels]
674 else:
675 return [np.array(array[self.row_indices[k], :])
/home/moebius/software/python-environments/for/lib/python3.5/site-packages/statsmodels/regression/mixed_linear_model.py in <listcomp>(.0)
671 if array.ndim == 1:
672 return [np.array(array[self.row_indices[k]])
--> 673 for k in self.group_labels]
674 else:
675 return [np.array(array[self.row_indices[k], :])
IndexError: index 49 is out of bounds for axis 1 with size 49
The problem is obviously that group=data['assistant'] is now too long and does not fit the design matrix build by patsy any more.
Q: How does the formula api make sure that the order in data['assistant'] and the design matrix produced by patsy always match? I don't know what patsy does under the hood, but is it allowed to change the order in which samples are given to it?
If there are missing values in data['assistant'] it also breaks.
In [69]: data.dropna(inplace=True)
In [70]: data.assistant[21] = np.nan
In [71]: fit = smf.mixedlm('response ~ sex + age + risk', groups=data['assistant'], data=data).fit()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-71-decde0c23284> in <module>()
----> 1 fit = smf.mixedlm('response ~ sex + age + risk', groups=data['assistant'], data=data).fit()
/home/moebius/software/python-environments/for/lib/python3.5/site-packages/statsmodels/regression/mixed_linear_model.py in from_formula(cls, formula, data, re_formula, subset, *args, **kwargs)
651 subset=None,
652 exog_re=exog_re,
--> 653 *args, **kwargs)
654
655 # expand re names to account for pairs of RE
/home/moebius/software/python-environments/for/lib/python3.5/site-packages/statsmodels/base/model.py in from_formula(cls, formula, data, subset, *args, **kwargs)
148 kwargs.update({'missing_idx': missing_idx,
149 'missing': missing})
--> 150 mod = cls(endog, exog, *args, **kwargs)
151 mod.formula = formula
152
/home/moebius/software/python-environments/for/lib/python3.5/site-packages/statsmodels/regression/mixed_linear_model.py in __init__(self, endog, exog, groups, exog_re, use_sqrt, missing, **kwargs)
528 # list of arrays, corresponding to the groups.
529 group_labels = list(set(groups))
--> 530 group_labels.sort()
531 row_indices = dict((s, []) for s in group_labels)
532 for i,g in enumerate(groups):
TypeError: unorderable types: str() < float()
A work around is to subset the data frame to only contain the variables needed in the model fit and drop all missings. It is just not very practical during model building and selection when a lot of variables are added and removed on the fly.
Maybe it would be more intuitive to define the grouping as a formula, too, say groups='~assistant' and that mixedlm works out the details by itself? I don't know. You are the experts.
Thank you for your help, your efforts, and a great package!
Activity
kshedden commentedon Nov 1, 2016
Thanks for your comments. I will look into this again. Last time I
checked it was difficult to get missing value handling to work correctly
with models that have auxiliary variables.
I believe that currently the groups argument can be a string containing the
grouping variable name, or the grouping variable itself. It might also be
possible to extend this to allow the group variable to be constructed on
the fly from a formula. I will keep that in mind.
Kerby
On Tue, Nov 1, 2016 at 11:28 AM, Thomas W. D. Möbius <
[email protected]> wrote: