Mixed effects GLM with python

Hi all,

I’d like to use Python to perform 2 mixed-effects (random effect) GLM. I see that nilearn has only glm.SecondLevelModel function which, as I understood, uses fixed effects.

Is there any nilearn or Python based solution (best if can deal also with surfaces) you recommend?

Thanks a lot!

Statsmodels has Mixed Effects GLM Generalized Linear Mixed Effects Models — statsmodels

Pymer4 is also a solid option! It uses R’s lme4 on the back end without needing to move between Python and R (i.e., working completely in Python).

1 Like

Ahoi hoi,

fresh out there and potentially very helpful wrt this: Brainstat! It’s a drastically updated version of surfstat and is now also available in python. You can work with surface, volume and parcel-based data and can run uni- and multivariate models which you can define comparably to pymer4 and statsmodels.

Disclaimer: I’m marginally involved in the development.

HTH, cheers, Peer

1 Like

That’s super! does it do RSA too? because I’ve twisted nilearn’s hands and legs to perform RSA and it’s working, but it’s nor nice neither pretty…

Ahoi hoi @urielias,

nope, it does not include RSA. For this I would recommend you have a look at the (new) rsatoolbox and the (new) feature-reweighted RSA toolbox (cc @Martin).

HTH, cheers, Peer


Hi Uri,
No Nilearn uses a classical random-effects model (ignoring first-level variance). See e.g.


This typically makes little difference wrt a full fledged mixed-effects model. Why do you say that it implements a fixed effects model ?

Random effects, true, a bad mistake…
“This typically makes little difference wrt a full fledged mixed-effects model” can you point some references so I can be more confident in this?

Thanks a lot,

Hi Uri,

I guess that as a last resort (since it would take you off python), you can also use FSL’s GLM. In order to make it work with surfaces, you would need to create a “fake nifti” with the connectome workbench.

wb_command -cifti-convert -to-nifti <cifti-in> <nifti-out>