Note

This page is a reference documentation. It only explains the class signature, and not how to use it. Please refer to the user guide for the big picture.

nilearn.maskers.NiftiMasker#

class nilearn.maskers.NiftiMasker(mask_img=None, runs=None, smoothing_fwhm=None, standardize=False, standardize_confounds=True, detrend=False, high_variance_confounds=False, low_pass=None, high_pass=None, t_r=None, target_affine=None, target_shape=None, mask_strategy='background', mask_args=None, dtype=None, memory_level=1, memory=Memory(location=None), verbose=0, reports=True, **kwargs)[source]#

Applying a mask to extract time-series from Niimg-like objects.

NiftiMasker is useful when preprocessing (detrending, standardization, resampling, etc.) of in-mask voxels is necessary. Use case: working with time series of resting-state or task maps.

Parameters:
mask_imgNiimg-like object, optional

See Input and output: neuroimaging data representation. Mask for the data. If not given, a mask is computed in the fit step. Optional parameters (mask_args and mask_strategy) can be set to fine tune the mask extraction. If the mask and the images have different resolutions, the images are resampled to the mask resolution. If target_shape and/or target_affine are provided, the mask is resampled first. After this, the images are resampled to the resampled mask.

runsnumpy.ndarray, optional

Add a run level to the preprocessing. Each run will be detrended independently. Must be a 1D array of n_samples elements.

smoothing_fwhmfloat, optional.

If smoothing_fwhm is not None, it gives the full-width at half maximum in millimeters of the spatial smoothing to apply to the signal.

standardize{‘zscore_sample’, ‘zscore’, ‘psc’, True, False}, default=False

Strategy to standardize the signal:

  • ‘zscore_sample’: The signal is z-scored. Timeseries are shifted to zero mean and scaled to unit variance. Uses sample std.

  • ‘zscore’: The signal is z-scored. Timeseries are shifted to zero mean and scaled to unit variance. Uses population std by calling default numpy.std with N - ddof=0.

  • ‘psc’: Timeseries are shifted to zero mean value and scaled to percent signal change (as compared to original mean signal).

  • True: The signal is z-scored (same as option zscore). Timeseries are shifted to zero mean and scaled to unit variance.

  • False: Do not standardize the data.

standardize_confoundsbool, default=True

If set to True, the confounds are z-scored: their mean is put to 0 and their variance to 1 in the time dimension.

high_variance_confoundsbool, default=False

If True, high variance confounds are computed on provided image with nilearn.image.high_variance_confounds and default parameters and regressed out.

detrendbool, optional

Whether to detrend signals or not.

low_passfloat or None, default=None

Low cutoff frequency in Hertz. If specified, signals above this frequency will be filtered out. If None, no low-pass filtering will be performed.

high_passfloat, default=None

High cutoff frequency in Hertz. If specified, signals below this frequency will be filtered out.

t_rfloat or None, default=None

Repetition time, in seconds (sampling period). Set to None if not provided.

target_affine3x3 or 4x4 numpy.ndarray, optional

This parameter is passed to image.resample_img. Please see the related documentation for details.

target_shape3-tuple of int, optional

This parameter is passed to image.resample_img. Please see the related documentation for details.

mask_strategy{“background”, “epi”, “whole-brain-template”,”gm-template”, “wm-template”}, optional

The strategy used to compute the mask:

  • “background”: Use this option if your images present a clear homogeneous background.

  • “epi”: Use this option if your images are raw EPI images

  • “whole-brain-template”: This will extract the whole-brain part of your data by resampling the MNI152 brain mask for your data’s field of view.

Note

This option is equivalent to the previous ‘template’ option which is now deprecated.

  • “gm-template”: This will extract the gray matter part of your data by resampling the corresponding MNI152 template for your data’s field of view.

    New in version 0.8.1.

  • “wm-template”: This will extract the white matter part of your data by resampling the corresponding MNI152 template for your data’s field of view.

    New in version 0.8.1.

Note

Depending on this value, the mask will be computed from nilearn.masking.compute_background_mask, nilearn.masking.compute_epi_mask, or nilearn.masking.compute_brain_mask.

Default=’background’.

mask_argsdict, optional

If mask is None, these are additional parameters passed to masking.compute_background_mask or masking.compute_epi_mask to fine-tune mask computation. Please see the related documentation for details.

dtype{dtype, “auto”}, optional

Data type toward which the data should be converted. If “auto”, the data will be converted to int32 if dtype is discrete and float32 if it is continuous.

memoryinstance of joblib.Memory, str, or pathlib.Path

Used to cache the masking process. By default, no caching is done. If a str is given, it is the path to the caching directory.

memory_levelint, default=1

Rough estimator of the amount of memory used by caching. Higher value means more memory for caching. Zero means no caching.

verboseint, default=0

Verbosity level (0 means no message).

reportsbool, default=True

If set to True, data is saved in order to produce a report.

kwargsdict

Keyword arguments to be passed to functions called within the masker. Kwargs prefixed with ‘clean__’ will be passed to clean. Within clean, kwargs prefixed with ‘butterworth__’ will be passed to the Butterworth filter (i.e., clean__butterworth__).

Attributes:
mask_img_nibabel.nifti1.Nifti1Image

The mask of the data, or the computed one.

affine_4x4 numpy.ndarray

Affine of the transformed image.

n_elements_int

The number of voxels in the mask.

New in version 0.9.2.

__init__(mask_img=None, runs=None, smoothing_fwhm=None, standardize=False, standardize_confounds=True, detrend=False, high_variance_confounds=False, low_pass=None, high_pass=None, t_r=None, target_affine=None, target_shape=None, mask_strategy='background', mask_args=None, dtype=None, memory_level=1, memory=Memory(location=None), verbose=0, reports=True, **kwargs)[source]#
generate_report()[source]#

Generate a report of the masker.

fit(imgs=None, y=None)[source]#

Compute the mask corresponding to the data.

Parameters:
imgslist of Niimg-like objects

See Input and output: neuroimaging data representation. Data on which the mask must be calculated. If this is a list, the affine is considered the same for all.

yNone

This parameter is unused. It is solely included for scikit-learn compatibility.

transform_single_imgs(imgs, confounds=None, sample_mask=None, copy=True)[source]#

Apply mask, spatial and temporal preprocessing.

Parameters:
imgs3D/4D Niimg-like object

See Input and output: neuroimaging data representation. Images to process. If a 3D niimg is provided, a singleton dimension will be added to the output to represent the single scan in the niimg.

confoundsCSV file or array-like or pandas.DataFrame, optional

This parameter is passed to signal.clean. Please see the related documentation for details: nilearn.signal.clean. shape: (number of scans, number of confounds)

sample_maskAny type compatible with numpy-array indexing, optional

shape: (number of scans - number of volumes removed, ) Masks the niimgs along time/fourth dimension to perform scrubbing (remove volumes with high motion) and/or non-steady-state volumes. This parameter is passed to signal.clean.

copybool, default=True

Indicates whether a copy is returned or not.

Returns:
region_signals2D numpy.ndarray

Signal for each voxel inside the mask. shape: (number of scans, number of voxels)

Warns:
DeprecationWarning

If a 3D niimg input is provided, the current behavior (adding a singleton dimension to produce a 2D array) is deprecated. Starting in version 0.12, a 1D array will be returned for 3D inputs.

fit_transform(X, y=None, confounds=None, sample_mask=None, **fit_params)[source]#

Fit to data, then transform it.

Parameters:
XNiimg-like object

See Input and output: neuroimaging data representation.

ynumpy array of shape [n_samples], optional

Target values.

confoundslist of confounds, optional

List of confounds (2D arrays or filenames pointing to CSV files). Must be of same length than imgs_list.

sample_masklist of sample_mask, optional

List of sample_mask (1D arrays) if scrubbing motion outliers. Must be of same length than imgs_list.

New in version 0.8.0.

Returns:
X_newnumpy array of shape [n_samples, n_features_new]

Transformed array.

get_metadata_routing()#

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:
routingMetadataRequest

A MetadataRequest encapsulating routing information.

get_params(deep=True)#

Get parameters for this estimator.

Parameters:
deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns:
paramsdict

Parameter names mapped to their values.

inverse_transform(X)[source]#

Transform the 2D data matrix back to an image in brain space.

This step only performs spatial unmasking, without inverting any additional processing performed by transform, such as temporal filtering or smoothing.

Parameters:
X1D/2D numpy.ndarray

Signal for each element in the mask. If a 1D array is provided, then the shape should be (number of elements,), and a 3D img will be returned. If a 2D array is provided, then the shape should be (number of scans, number of elements), and a 4D img will be returned. See Input and output: neuroimaging data representation.

Returns:
imgTransformed image in brain space.
set_fit_request(*, imgs='$UNCHANGED$')#

Request metadata passed to the fit method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

New in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
imgsstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for imgs parameter in fit.

Returns:
selfobject

The updated object.

set_output(*, transform=None)#

Set output container.

See Introducing the set_output API for an example on how to use the API.

Parameters:
transform{“default”, “pandas”}, default=None

Configure output of transform and fit_transform.

  • “default”: Default output format of a transformer

  • “pandas”: DataFrame output

  • “polars”: Polars output

  • None: Transform configuration is unchanged

New in version 1.4: “polars” option was added.

Returns:
selfestimator instance

Estimator instance.

set_params(**params)#

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.

Parameters:
**paramsdict

Estimator parameters.

Returns:
selfestimator instance

Estimator instance.

set_transform_request(*, confounds='$UNCHANGED$', imgs='$UNCHANGED$', sample_mask='$UNCHANGED$')#

Request metadata passed to the transform method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to transform.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

New in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
confoundsstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for confounds parameter in transform.

imgsstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for imgs parameter in transform.

sample_maskstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for sample_mask parameter in transform.

Returns:
selfobject

The updated object.

transform(imgs, confounds=None, sample_mask=None)[source]#

Apply mask, spatial and temporal preprocessing.

Parameters:
imgs3D/4D Niimg-like object

See Input and output: neuroimaging data representation. Images to process. If a 3D niimg is provided, a singleton dimension will be added to the output to represent the single scan in the niimg.

confoundsCSV file or array-like, optional

This parameter is passed to signal.clean. Please see the related documentation for details. shape: (number of scans, number of confounds)

sample_maskAny type compatible with numpy-array indexing, optional

shape: (number of scans - number of volumes removed, ) Masks the niimgs along time/fourth dimension to perform scrubbing (remove volumes with high motion) and/or non-steady-state volumes. This parameter is passed to signal.clean.

New in version 0.8.0.

Returns:
region_signals2D numpy.ndarray

Signal for each element. shape: (number of scans, number of elements)

Warns:
DeprecationWarning

If a 3D niimg input is provided, the current behavior (adding a singleton dimension to produce a 2D array) is deprecated. Starting in version 0.12, a 1D array will be returned for 3D inputs.

Examples using nilearn.maskers.NiftiMasker#

The haxby dataset: different multi-class strategies

The haxby dataset: different multi-class strategies

Searchlight analysis of face vs house recognition

Searchlight analysis of face vs house recognition

ROI-based decoding analysis in Haxby et al. dataset

ROI-based decoding analysis in Haxby et al. dataset

Voxel-Based Morphometry on Oasis dataset

Voxel-Based Morphometry on Oasis dataset

Encoding models for visual stimuli from Miyawaki et al. 2008

Encoding models for visual stimuli from Miyawaki et al. 2008

Reconstruction of visual stimuli from Miyawaki et al. 2008

Reconstruction of visual stimuli from Miyawaki et al. 2008

Producing single subject maps of seed-to-voxel correlation

Producing single subject maps of seed-to-voxel correlation

First level analysis of a complete BIDS dataset from openneuro

First level analysis of a complete BIDS dataset from openneuro

Simple example of NiftiMasker use

Simple example of NiftiMasker use

Understanding NiftiMasker and mask computation

Understanding NiftiMasker and mask computation

Multivariate decompositions: Independent component analysis of fMRI

Multivariate decompositions: Independent component analysis of fMRI

Massively univariate analysis of a calculation task from the Localizer dataset

Massively univariate analysis of a calculation task from the Localizer dataset

Massively univariate analysis of a motor task from the Localizer dataset

Massively univariate analysis of a motor task from the Localizer dataset

NeuroVault cross-study ICA maps

NeuroVault cross-study ICA maps

Massively univariate analysis of face vs house recognition

Massively univariate analysis of face vs house recognition

Advanced decoding using scikit learn

Advanced decoding using scikit learn

Beta-Series Modeling for Task-Based Functional Connectivity and Decoding

Beta-Series Modeling for Task-Based Functional Connectivity and Decoding