Repository navigation
Open
Labels
Description
statsmodels.mixedlm generates different results under Python 2.7 and Python 3.4. Moreover, in Python 3.4, the model does not converge when re_formula is used with variable slope.
Here is a simple example:
import statsmodels.formula.api as smf
import pandas as pd
import numpy as np
from copy import deepcopy
np.random.seed(seed=0)
data1 = pd.DataFrame(columns=['x','y','id'])
data2 = pd.DataFrame(columns=['x','y','id'])
data1['x'] = np.random.normal(size=100)
data1['y'] = deepcopy(data1['x'])*3 + np.random.normal(size=100)
data1['id'] = np.ones(100)
data2['x'] = np.random.normal(size=100)
data2['y'] = deepcopy(data2['x'])*2 + np.random.normal(size=100)
data2['id'] = np.ones(100)*2
data = pd.concat([data1,data2])
data = data.reset_index(drop=True)
md = smf.mixedlm('y ~ x', data, groups=data['id'], re_formula='~ x')
mdf = md.fit(method='cg')
print(mdf.summary())Python 2.7 converges and generates the following results:
Mixed Linear Model Regression Results
==============================================================
Model: MixedLM Dependent Variable: y
No. Observations: 200 Method: REML
No. Groups: 2 Scale: 0.9636
Min. group size: 100 Likelihood: -286.7528
Max. group size: 100 Converged: Yes
Mean group size: 100.0
--------------------------------------------------------------
Coef. Std.Err. z P>|z| [0.025 0.975]
--------------------------------------------------------------
Intercept -0.048 0.532 -0.091 0.928 -1.091 0.994
x 2.631 1.673 1.572 0.116 -0.649 5.911
Intercept RE 0.558
Intercept RE x x RE 1.660
x RE 5.597
==============================================================
Python 3.4 does not converge and gives these results:
/usr/local/lib/python3.4/dist-packages/statsmodels/base/model.py:496: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals
"Check mle_retvals", ConvergenceWarning)
/usr/local/lib/python3.4/dist-packages/statsmodels/base/model.py:496: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals
"Check mle_retvals", ConvergenceWarning)
/usr/local/lib/python3.4/dist-packages/statsmodels/base/model.py:496: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals
"Check mle_retvals", ConvergenceWarning)
/usr/local/lib/python3.4/dist-packages/statsmodels/base/model.py:496: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals
"Check mle_retvals", ConvergenceWarning)
Mixed Linear Model Regression Results
=========================================================
Model: MixedLM Dependent Variable: y
No. Observations: 200 Method: REML
No. Groups: 2 Scale: 0.9680
Min. group size: 100 Likelihood: -284.9909
Max. group size: 100 Converged: No
Mean group size: 100.0
---------------------------------------------------------
Coef. Std.Err. z P>|z| [0.025 0.975]
---------------------------------------------------------
Intercept -0.057
x 2.620
Intercept RE 0.034
Intercept RE x x RE 0.129
x RE 0.482
=========================================================
Which are pretty different for some of the parameters. Any ideas?
Activity
kshedden commentedon Apr 10, 2017
sosata commentedon Apr 11, 2017
I have actually tested this on a real human subject dataset with 206 groups, and the results were drastically different between Python 2.7 and 3.4.
Plus, although I agree that this simulated dataset is unusual, it does not make sense that the same package under two different versions of Python gives different results.
josef-pkt commentedon Apr 11, 2017
What are your scipy versions in Python 2.7 and 3.4?
Unless there is an integer division or similar bug, then the python version is irrelevant. However, if the optimization problems are not "nice", then small changes across
scipy.optimizeversions can affect optimization and convergence. In well behaved problems the optimizer shouldn't have much effect and should converge to the same values (subject to noise), but if the parameters are not well identified or at the boundary, then small numerical differences could have large effects.(That's just in general. I'm not familiar enough with optimization problems in MixedLM to say anything specific.)
kshedden commentedon Apr 11, 2017
sosata commentedon Apr 11, 2017
Thanks for your replies, Kerby and Josef.
The versions are different. In Python 2.7, the statsmodels is 0.6.1 and scipy is 0.17.1. In Python 3.4, these are 0.8.0 and 0.19.0 respectively. I will try to upgrade the packages in Python 2.7 and see what happens.
kshedden commentedon Apr 11, 2017
sosata commentedon Apr 11, 2017
But it is actually the older version that converges. The 0.8.0 version is the one that doesn't converge.
kshedden commentedon Apr 11, 2017
sosata commentedon Apr 11, 2017
The model under statsmodels 0.6.1 gives the following gradients:
and the model under statsmodels 0.8.0 gives these:
It seems none of these have converged. Although, I don't understand why one generates 5 gradients and the other 3.
kshedden commentedon Apr 11, 2017
sosata commentedon Apr 11, 2017
So you suggest that we use the results of 0.8.0 even though it says that it hasn't converged?
josef-pkt commentedon Apr 11, 2017
I was playing a bit with the example
It looks to me that the covariance of the random effects is not well converged or well identified, but the local solution still looks good.
The reported Hessian in the optimization is not positive definite, but the part of the hessian for the fixed effects parameters seems to be fine.
AFAIK, the fixed effects parameters are still consistently estimated with "incorrect" random effects or misspecified residual correlation. So the fixed effects parameter are pretty close across different specification. However, the cov_params and standard errors differ quite a bit. So those will still be affected by imprecise estimation of the random effects.
cluster robust standard errors are on the larger end compared to the above. But with only two clusters, they shouldn't be very reliable.
sosata commentedon Apr 14, 2017
Alright, I also tried MATLAB and R to fit the mixed effects model to our data. They produce different results from both statsmodels 6 and 8, however they are consistent with each other. Therefore it seems there is a problem with the mixedlm function in statsmodels that needs to be fixed.
kshedden commentedon Apr 14, 2017
sosata commentedon Apr 17, 2017
Sure. This is how we are using each:
R:
MATLAB:
Python:
In all three, data we want to predict y from x in data, with subject specifying the groups.
joergdietrich commentedon Mar 6, 2018
@kshedden To further add to this issue, the generated mixed lm example (pulled from current master, #4204) shows non-convergence and different results in the lme4 comparison.
This is after running the notebook locally with statsmodels 0.8.0, scipy 1.0.0 under python 3.6.4.
kshedden commentedon Mar 7, 2018
@joergdietrich Thanks for the report. We would like this to be as consistent as possible with other packages. However the sitka example in the notebook and the simulated example above both have their MLE and RMLE on the boundary of the parameter space. This may be somewhat common in practice, but it leads to many computational and statistical issues.
I went back to the simulated example above and ran it in R and in statsmodels using 3 different optimizers. The optimized values of the log-likelihoods are:
The final gradient values (for the transformed parameters in the optimization) are
So CG is pretty well converged but the others are not quite there.
Looking at the fitted parameters, here is what we get in statsmodels under CG:
And here is what R produces:
These two solutions achieve essentially the same likelihood value, and the parameter estimates themselves are also nearly identical.
I hope that the discepancies that people are seeing are not just due to misreading the output. We report variance and covariances, so, e.g. the correlation between the two random effects in our output is
the is the same correlation parameter that R reports as 1, so it is as close as we can hope for in my view.
I haven't looked at the sitka example in a while, but my recollection is that we achieve a slightly higher log-likelihood value than R.
We have quite a bit of empirical data here and elsewhere that the log-likelihood, score, and hessian are correctly implemented for the MLE and RMLE. However the optimizers that we use (from scipy) are intended for problems in which the optimum is in the interior of the parameter space. When the optimum is on the boundary, the MLE/RMLE may not even be unique, and even if it is unique, there is no guarantee that these algorithms will find it. I don't know what optimizer R and Matlab are using, but as far as I know it is some type of first order method similar to what scipy uses and therefore is subject to the same limitations.
I believe we are also all using the same transformed objective function, which profiles out the scale parameter then represents the random effects covariance matrix in terms of its Cholesky factor.
We should probably restructure the notebooks so that the introductory notebook uses examples that are not on the boundary, then we could have a separate notebook discussing these more advanced issues.
joergdietrich commentedon Mar 7, 2018
@kshedden Thanks for the detailed reply! I'm coming to this as somebody who wants to learn about MixedLM and found lots of examples on the web using R. Not knowing a lot of R, I wanted to understand how these examples match to the different syntax of specifying random effects etc. in statsmodels. Having a mismatch between lme4 and statsmodels is quite confusing in this case.
I didn't look at the Sitka data set. I gave up after I couldn't make the Pigs analysis match (I'm not sure what simulated data you refer to. The Pigs data seem to be a real data set.).
Quite different output in R:
The notebook then goes on to say
and I can't find these numbers in the statsmodels output. I suspect those numbers may have come out of some earlier scipy version. So this is all quite confusing for somebody like me, who wants to map the many R examples on the web to statsmodels. I think a more introductory notebook, as you suggested above, would indeed be helpful.
Greetings from a former West Hall (Physics) resident.
kshedden commentedon Mar 7, 2018
@joergdietrich the example you are showing here has a convergence issue. With the random slope for Time, the fit converges using lbfgs, cg, and powell optimizers, but not using the bfgs optimizer which is the default. (see code below). If we get enough evidence that this is a poor default, we could change it. Another possibiity is that we need to provide better starting values, or perhaps internally standardize the covariates. Or perhaps we need to use a hybrid optimization approach, e.g. start with powell then switch to cg. Thanks for pointing this out.
kshedden commentedon Mar 7, 2018
Another comment on the dietox data -- if we center Time, which is probably the right thing to do anyway on methodological grounds, all four optimization methods converge and agree with R.
I have a pending PR that adds unit tests for the dietox data. The comments show how each field of the statsmodels fit can be programmatically extracted from the lmer object:
https://github.com/kshedden/statsmodels/blob/2066531794d8ce50fbaf9e40d50771ca06a4dcea/statsmodels/regression/tests/test_lme.py#L366
kshedden commentedon Mar 7, 2018
I don't currently have a way to run Jupyter. If someone wants to clean up the notebook and make a PR that would be great.