Nilearn
Nilearn is a Python library for statistical learning with neuroimaging data. It provides tools for general linear model (GLM) based analysis and leverages the scikit-learn toolbox for multivariate statistics, including predictive modeling, classification, decoding, and connectivity analysis. The current stable version is 0.13.1, and releases occur regularly, often including new features, enhancements, and deprecations.
Common errors
-
ImportError: cannot import name plotting from 'nilearn'
cause Attempting to import a specific plotting function directly from `nilearn` (e.g., `from nilearn import plot_img`) or from an outdated submodule path (e.g., `from nilearn.plotting.image import plot_img`) after refactoring.fixImport the `plotting` module directly and then access functions through it: `from nilearn import plotting; plotting.plot_img(...)`. -
ImportError: cannot import name 'NiftiMasker' from 'nilearn.input_data'
cause The `NiftiMasker` class, along with other masker objects, has been moved to the `nilearn.maskers` module.fixChange the import statement to `from nilearn.maskers import NiftiMasker`. -
Killed: 9 (or similar out-of-memory errors during masking/resampling)
cause Processing large neuroimaging datasets can be memory-intensive, especially during spatial resampling or when working with high-resolution masks without downsampling.fixReduce data resolution using `target_affine` and/or `target_shape` parameters in maskers or `nilearn.image.resample_img`. Consider processing fewer subjects at a time or using a server with more RAM. For `NiftiMasker`, explicitly setting `dtype='auto'` can save memory by forcing `float32`. -
ModuleNotFoundError: No module named 'nilearn'
cause Nilearn is not installed in the active Python environment, or there's a naming conflict with a local file/directory named `nilearn.py` or `nilearn`.fixEnsure Nilearn is installed via `pip install -U nilearn` (or `conda install nilearn`). Check your current working directory for any files or folders named 'nilearn' that might shadow the installed package.
Warnings
- breaking Nilearn 0.13.0 dropped support for Python 3.9. Users on Python 3.9 or older versions will encounter installation errors or unexpected behavior.
- breaking The `nilearn.input_data` module has been refactored and masker classes (e.g., `NiftiMasker`, `NiftiLabelsMasker`) are now located in `nilearn.maskers`. Direct imports from `nilearn.input_data` will raise an `ImportError`.
- deprecated The `standardize` parameter in various functions and maskers (e.g., `plot_carpet`, `NiftiMasker`) no longer accepts boolean `True`/`False`. Its default behavior changed, and specific string values like `'zscore_sample'` or `None` should be used.
- breaking Default values for parameters in `fetch_atlas_yeo_2011`, `fetch_atlas_craddock_2012`, and `fetch_atlas_smith_2009` have changed in 0.13.0. For instance, `n_networks` and `thickness` in `fetch_atlas_yeo_2011` now default to `7` and `'thick'` respectively, instead of `None`.
- gotcha Plotting functions like `plot_img` now accept a `radiological` parameter (defaulting to `False`) which inverts the x-axis and L/R annotations for radiological convention. If you rely on the old orientation, ensure `radiological=False` is set explicitly.
Install
-
pip install -U nilearn -
conda create -n nilearn_env python=3.10 conda activate nilearn_env pip install -U nilearn
Imports
- datasets
from nilearn import datasets
- plotting
from nilearn.plotting.image import plot_img
from nilearn import plotting
- NiftiMasker
from nilearn.input_data import NiftiMasker
from nilearn.maskers import NiftiMasker
- image
from nilearn import image
- Decoder
from nilearn.decoding import Decoder
Quickstart
import warnings
warnings.filterwarnings("ignore", message="The provided image has no sform in its header.")
from nilearn import datasets, plotting, maskers
# 1. Fetch a sample fMRI dataset (Haxby dataset)
haxby_dataset = datasets.fetch_haxby(subjects=1, fetch_stimuli=False)
fmri_filename = haxby_dataset.func[0]
anat_filename = haxby_dataset.anat[0]
mask_filename = haxby_dataset.mask_vt[0]
# 2. Extract signals using NiftiMasker
# The mask_strategy='epi' is often more robust for EPI images
masker = maskers.NiftiMasker(mask_img=mask_filename, smoothing_fwhm=6, standardize='zscore_sample')
fmri_data_masked = masker.fit_transform(fmri_filename)
# 3. Plot the anatomical image and overlay the mask
print(f"Shape of masked fMRI data: {fmri_data_masked.shape}")
# Plotting the anatomical image with the mask overlay
plotting.plot_anat(
anat_filename,
title="Anatomical image with mask overlay",
display_mode='ortho',
cut_coords=(0, 0, 0),
output_file=None # Change to a filename like 'anat_with_mask.png' to save
)
# Plotting a single volume from the fMRI data
first_fmri_volume = image.index_img(fmri_filename, 0)
plotting.plot_img(
first_fmri_volume,
bg_img=anat_filename,
title="First fMRI volume",
display_mode='ortho',
cut_coords=(0, 0, 0),
output_file=None # Change to a filename like 'first_fmri_volume.png' to save
)
# You can also show the plots (usually at the end of a script or in an interactive session)
# plotting.show()