.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/02_decoding/plot_haxby_searchlight.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. or to run this example in your browser via Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_02_decoding_plot_haxby_searchlight.py: Searchlight analysis of face vs house recognition ================================================= Searchlight analysis requires fitting a classifier a large amount of times. As a result, it is an intrinsically slow method. In order to speed up computing, in this example, Searchlight is run only on one slice on the :term:`fMRI` (see the generated figures). .. GENERATED FROM PYTHON SOURCE LINES 14-16 Load Haxby dataset ------------------ .. GENERATED FROM PYTHON SOURCE LINES 16-33 .. code-block:: Python import pandas as pd from nilearn.datasets import fetch_haxby from nilearn.image import get_data, load_img, new_img_like # We fetch 2nd subject from the Haxby datasets (which is default) haxby_dataset = fetch_haxby() # print basic information on the dataset print(f"Anatomical nifti image (3D) is located at: {haxby_dataset.mask}") print(f"Functional nifti image (4D) is located at: {haxby_dataset.func[0]}") fmri_filename = haxby_dataset.func[0] labels = pd.read_csv(haxby_dataset.session_target[0], sep=" ") y = labels["labels"] run = labels["chunks"] .. rst-class:: sphx-glr-script-out .. code-block:: none [fetch_haxby] Dataset directory found: /home/runner/work/nilearn/nilearn/nilearn_data/haxby2001 Anatomical nifti image (3D) is located at: /home/runner/work/nilearn/nilearn/nilearn_data/haxby2001/mask.nii.gz Functional nifti image (4D) is located at: /home/runner/work/nilearn/nilearn/nilearn_data/haxby2001/subj2/bold.nii.gz .. GENERATED FROM PYTHON SOURCE LINES 34-36 Restrict to faces and houses ---------------------------- .. GENERATED FROM PYTHON SOURCE LINES 36-43 .. code-block:: Python from nilearn.image import index_img condition_mask = y.isin(["face", "house"]) fmri_img = index_img(fmri_filename, condition_mask) y, run = y[condition_mask], run[condition_mask] .. GENERATED FROM PYTHON SOURCE LINES 44-50 Prepare masks ------------- - mask_img is the original mask - process_mask_img is a subset of mask_img, it contains the voxels that should be processed (we only keep the slice z = 29 and the back of the brain to speed up computation) .. GENERATED FROM PYTHON SOURCE LINES 50-62 .. code-block:: Python import numpy as np mask_img = load_img(haxby_dataset.mask) # .astype() makes a copy. process_mask = get_data(mask_img).astype(int) picked_slice = 29 process_mask[..., (picked_slice + 1) :] = 0 process_mask[..., :picked_slice] = 0 process_mask[:, 30:] = 0 process_mask_img = new_img_like(mask_img, process_mask) .. rst-class:: sphx-glr-script-out .. code-block:: none /home/runner/work/nilearn/nilearn/examples/02_decoding/plot_haxby_searchlight.py:60: UserWarning: Data array used to create a new image contains 64-bit ints. This is likely due to creating the array with numpy and passing `int` as the `dtype`. Many tools such as FSL and SPM cannot deal with int64 in Nifti images, so for compatibility the data has been converted to int32. .. GENERATED FROM PYTHON SOURCE LINES 63-71 Searchlight computation ----------------------- Make processing parallel .. warning:: As each thread will print its progress, n_jobs > 1 could mess up the information output. .. GENERATED FROM PYTHON SOURCE LINES 71-73 .. code-block:: Python n_jobs = 2 .. GENERATED FROM PYTHON SOURCE LINES 74-81 Define the cross-validation scheme used for validation. Here we use a KFold cross-validation on the run, which corresponds to splitting the samples in 4 folds and make 4 runs using each fold as a test set once and the others as learning sets The radius is the one of the Searchlight sphere that will scan the volume. .. GENERATED FROM PYTHON SOURCE LINES 81-97 .. code-block:: Python from sklearn.model_selection import KFold from nilearn.decoding import SearchLight cv = KFold(n_splits=4) searchlight = SearchLight( mask_img, process_mask_img=process_mask_img, radius=5.6, n_jobs=n_jobs, verbose=1, cv=cv, ) searchlight.fit(fmri_img, y) .. rst-class:: sphx-glr-script-out .. code-block:: none [Parallel(n_jobs=2)]: Using backend LokyBackend with 2 concurrent workers. [Parallel(n_jobs=2)]: Done 2 out of 2 | elapsed: 4.4s remaining: 0.0s [Parallel(n_jobs=2)]: Done 2 out of 2 | elapsed: 4.4s finished .. raw:: html
SearchLight(cv=KFold(n_splits=4, random_state=None, shuffle=False),
                mask_img=<nibabel.nifti1.Nifti1Image object at 0x7f2db0044910>,
                n_jobs=2,
                process_mask_img=<nibabel.nifti1.Nifti1Image object at 0x7f2db00467a0>,
                radius=5.6, verbose=1)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.


.. GENERATED FROM PYTHON SOURCE LINES 98-102 Visualization ------------- After fitting the searchlight, we can access the searchlight scores as a NIfTI image using the ``scores_img_`` attribute. .. GENERATED FROM PYTHON SOURCE LINES 102-104 .. code-block:: Python scores_img = searchlight.scores_img_ .. GENERATED FROM PYTHON SOURCE LINES 105-106 Use the :term:`fMRI` mean image as a surrogate of anatomical data .. GENERATED FROM PYTHON SOURCE LINES 106-110 .. code-block:: Python from nilearn.image import mean_img mean_fmri = mean_img(fmri_img) .. GENERATED FROM PYTHON SOURCE LINES 111-113 Because scores are not a zero-center test statistics, we cannot use plot_stat_map .. GENERATED FROM PYTHON SOURCE LINES 113-131 .. code-block:: Python from nilearn.plotting import plot_img, plot_stat_map, show plot_img( scores_img, bg_img=mean_fmri, title="Searchlight scores image", display_mode="z", cut_coords=[-9], vmin=0.2, vmax=0.9, cmap="inferno", threshold=0.2, black_bg=True, colorbar=True, ) show() .. image-sg:: /auto_examples/02_decoding/images/sphx_glr_plot_haxby_searchlight_001.png :alt: plot haxby searchlight :srcset: /auto_examples/02_decoding/images/sphx_glr_plot_haxby_searchlight_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 132-134 F-scores computation -------------------- .. GENERATED FROM PYTHON SOURCE LINES 134-168 .. code-block:: Python from sklearn.feature_selection import f_classif from nilearn.maskers import NiftiMasker # For decoding, standardizing is often very important nifti_masker = NiftiMasker( mask_img=mask_img, runs=run, standardize="zscore_sample", memory="nilearn_cache", memory_level=1, verbose=1, ) fmri_masked = nifti_masker.fit_transform(fmri_img) _, p_values = f_classif(fmri_masked, y) p_values = -np.log10(p_values) p_values[p_values > 10] = 10 p_unmasked = get_data(nifti_masker.inverse_transform(p_values)) # F_score results p_ma = np.ma.array(p_unmasked, mask=np.logical_not(process_mask)) f_score_img = new_img_like(mean_fmri, p_ma) plot_stat_map( f_score_img, mean_fmri, title="F-scores", display_mode="z", cut_coords=[-9], cmap="inferno", ) show() .. image-sg:: /auto_examples/02_decoding/images/sphx_glr_plot_haxby_searchlight_002.png :alt: plot haxby searchlight :srcset: /auto_examples/02_decoding/images/sphx_glr_plot_haxby_searchlight_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none [NiftiMasker.wrapped] Loading data from [NiftiMasker.wrapped] Loading mask from [NiftiMasker.wrapped] Resampling mask [NiftiMasker.wrapped] Finished fit ________________________________________________________________________________ [Memory] Calling nilearn.maskers.nifti_masker.filter_and_mask... filter_and_mask(, , { 'clean_args': None, 'clean_kwargs': {}, 'cmap': 'gray', 'detrend': False, 'dtype': None, 'high_pass': None, 'high_variance_confounds': False, 'low_pass': None, 'reports': True, 'runs': 21 0 22 0 23 0 24 0 25 0 .. 1398 11 1399 11 1400 11 1401 11 1402 11 Name: chunks, Length: 216, dtype: int64, 'smoothing_fwhm': None, 'standardize': 'zscore_sample', 'standardize_confounds': True, 't_r': None, 'target_affine': None, 'target_shape': None}, memory_level=1, memory=Memory(location=nilearn_cache/joblib), verbose=1, confounds=None, sample_mask=None, copy=True, sklearn_output_config=None) [NiftiMasker.wrapped] Loading data from [NiftiMasker.wrapped] Extracting region signals [NiftiMasker.wrapped] Cleaning extracted signals __________________________________________________filter_and_mask - 0.8s, 0.0min [NiftiMasker.inverse_transform] Computing image from signals ________________________________________________________________________________ [Memory] Calling nilearn.masking.unmask... unmask(array([5.229069, ..., 0.326513], dtype=float32), ) ___________________________________________________________unmask - 0.0s, 0.0min .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 13.554 seconds) **Estimated memory usage:** 1031 MB .. _sphx_glr_download_auto_examples_02_decoding_plot_haxby_searchlight.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/nilearn/nilearn/0.14.1?urlpath=lab/tree/notebooks/auto_examples/02_decoding/plot_haxby_searchlight.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_haxby_searchlight.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_haxby_searchlight.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_haxby_searchlight.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_