CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
adasegroup

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: adasegroup/NEUROML2022
Path: blob/main/seminar6/extraxct_ica_components.ipynb
Views: 63
Kernel: Python 3 (ipykernel)
!pip install nilearn
Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/ Collecting nilearn Downloading nilearn-0.9.2-py3-none-any.whl (9.6 MB) |████████████████████████████████| 9.6 MB 6.8 MB/s Requirement already satisfied: lxml in /usr/local/lib/python3.7/dist-packages (from nilearn) (4.9.1) Requirement already satisfied: scikit-learn>=0.22 in /usr/local/lib/python3.7/dist-packages (from nilearn) (1.0.2) Requirement already satisfied: joblib>=0.15 in /usr/local/lib/python3.7/dist-packages (from nilearn) (1.1.0) Requirement already satisfied: requests>=2 in /usr/local/lib/python3.7/dist-packages (from nilearn) (2.23.0) Requirement already satisfied: scipy>=1.5 in /usr/local/lib/python3.7/dist-packages (from nilearn) (1.7.3) Requirement already satisfied: nibabel>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from nilearn) (3.0.2) Requirement already satisfied: pandas>=1.0 in /usr/local/lib/python3.7/dist-packages (from nilearn) (1.3.5) Requirement already satisfied: numpy>=1.18 in /usr/local/lib/python3.7/dist-packages (from nilearn) (1.21.6) Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=1.0->nilearn) (2022.2.1) Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=1.0->nilearn) (2.8.2) Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=1.0->nilearn) (1.15.0) Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2->nilearn) (1.24.3) Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2->nilearn) (3.0.4) Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2->nilearn) (2.10) Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2->nilearn) (2022.6.15) Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.22->nilearn) (3.1.0) Installing collected packages: nilearn Successfully installed nilearn-0.9.2
from pathlib import Path from nilearn import image import nilearn from nilearn import plotting import numpy as np import os import matplotlib.pyplot as plt
try: import google.colab IN_COLAB = True except ImportError: IN_COLAB = False from pathlib import Path if IN_COLAB: google.colab.drive.mount("/content/drive") # Change this if you created the shortcut in a different location AUX_DATA_ROOT = Path("/content/drive/My Drive/NEUROML") assert AUX_DATA_ROOT.is_dir(), "Have you forgot to 'Add a shortcut to Drive'?" import sys sys.path.append(str(AUX_DATA_ROOT)) else: AUX_DATA_ROOT = Path(".")
Mounted at /content/drive

Seminar 6.1 : Extract ICA components from fMRI data

subject_path =AUX_DATA_ROOT / 'data/sub-A00037224_task-rest_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz' subject_path =AUX_DATA_ROOT / 'data/sub-A00037224_task-rest_space-MNI152NLin6Asym_desc-smoothAROMAnonaggr_bold.nii.gz'
fmri_file =image.load_img(subject_path)
fmri_file.shape
(91, 109, 91, 150)
first_fmri = image.index_img(fmri_file, 2) print(first_fmri.shape)
(91, 109, 91)
nilearn.plotting.plot_img(first_fmri, cut_coords=(0,0,0))
<nilearn.plotting.displays._slicers.OrthoSlicer at 0x7f299a08bf50>
Image in a Jupyter notebook
from nilearn.maskers import NiftiMasker # # This is fmri timeseries data: the background has not been removed yet, # # thus we need to use mask_strategy='epi' to compute the mask from the # # EPI images masker = NiftiMasker(smoothing_fwhm=8, memory='nilearn_cache', memory_level=1, mask_strategy='epi', standardize=True) data_masked = masker.fit_transform(fmri_file)
/usr/local/lib/python3.7/dist-packages/nilearn/maskers/nifti_masker.py:453: UserWarning: Persisting input arguments took 1.04s to run. If this happens often in your code, it can cause performance problems (results will be correct in all cases). The reason for this is probably some large input arguments for a wrapped function (e.g. large strings). THIS IS A JOBLIB ISSUE. If you can, kindly provide the joblib's team with an example so that they can fix the problem. imgs, verbose=max(0, self.verbose - 1), **mask_args /usr/local/lib/python3.7/dist-packages/nilearn/maskers/nifti_masker.py:589: UserWarning: Persisting input arguments took 1.12s to run. If this happens often in your code, it can cause performance problems (results will be correct in all cases). The reason for this is probably some large input arguments for a wrapped function (e.g. large strings). THIS IS A JOBLIB ISSUE. If you can, kindly provide the joblib's team with an example so that they can fix the problem. dtype=self.dtype,
data_masked.shape
(150, 551376)
from sklearn.decomposition import FastICA n_components = 30 ica = FastICA(n_components=n_components, random_state=42) components_masked = ica.fit_transform(data_masked.T).T
components_masked.shape
(30, 551376)
# Normalize estimated components, for thresholding to make sense components_masked -= components_masked.mean(axis=0) components_masked /= components_masked.std(axis=0) # Threshold components_masked[np.abs(components_masked) < 0.8] = 0
plt.hist(components_masked[4], bins=10)
(array([1.05000e+02, 1.51400e+03, 4.35170e+04, 2.30037e+05, 2.02732e+05, 4.95990e+04, 1.27720e+04, 6.45600e+03, 3.63400e+03, 1.01000e+03]), array([-0.0056281 , -0.00426328, -0.00289846, -0.00153365, -0.00016883, 0.00119599, 0.0025608 , 0.00392562, 0.00529044, 0.00665526, 0.00802007]), <a list of 10 Patch objects>)
Image in a Jupyter notebook
component_img = masker.inverse_transform(components_masked)
component_img.shape
(91, 109, 91, 30)
first_component = image.index_img(component_img, 1) print(first_component.shape)
(91, 109, 91)
nilearn.plotting.plot_img(first_component, cut_coords=(0,0,0))
<nilearn.plotting.displays._slicers.OrthoSlicer at 0x7f2999f30890>
Image in a Jupyter notebook
from nilearn import image from nilearn.plotting import plot_stat_map, show
# Use the mean as a background mean_img = image.mean_img(subject_path) plot_stat_map(image.index_img(component_img, 0), mean_img) plot_stat_map(image.index_img(component_img, 1), mean_img) show()
Image in a Jupyter notebookImage in a Jupyter notebook