# ica.get_explained_variance_ratio for individual ICA components

Hi, everyone!
First time poster here :). I was wondering how to print a list or a make a dictionary of all ICA components and their respective variances. The problem seems to be that ica.get_explained_variance_ratio only calculates variance jointly across all the specified components. Also, I am aware that the sum of all variances does not amount to 100% from previous examples :).

# Explained variance ratio of individual components

ch_type = ‘mag’
components = range(ica.n_components_)

for components in range(ica.n_components_):
explained_comp = ica.get_explained_variance_ratio(filt_data, components=[components], ch_type=ch_type)
ratios = explained_var_ratio[ch_type] # this seems to return just cumulative value
print(
f’ICA component {components} explains {ratios}’
)
Output for all components is: ICA component () explains 0.0401906384322992
Thanks for any input or suggestions!

Hello, your

``````explained_comp
``````

should already contain what you want. Also you don’t need to change the component index to a list.

I don’t know where your `explained_var_ratio` comes from.

Best wishes,
Richard

1 Like

Hi, thanks for your quick response :). I was using the example found in this link, under the title “Looking at the ICA solution” (Repairing artifacts with ICA — MNE 1.7.1 documentation), however, it only calculates cumulative variance of components for specified channels (“mag”, “eeg”), but I would like to see the explained variance ratios of all the chosen components individually for “meg” (if n_components = 20, I would like to make a list/dict of the components and their respective variances. Can you maybe offer some help? Thanks in advance!

You can do something like this:

``````# %%
import pandas as pd

import mne
from mne.preprocessing import ICA

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = (
sample_data_folder / "MEG" / "sample" / "sample_audvis_filt-0-40_raw.fif"
)
raw = (
.crop(tmax=60.0)
.pick(picks=["mag", "eeg", "stim", "eog"])
)

filt_raw = raw.copy().filter(l_freq=1.0, h_freq=None)

ica = ICA(random_state=97)
ica.fit(filt_raw)

# %%
ch_types = ("mag", "eeg")
var_explained = pd.DataFrame(
columns=ch_types, index=pd.RangeIndex(ica.n_components_, name="Component")
)
for component_idx in range(ica.n_components_):
ratios = ica.get_explained_variance_ratio(filt_raw, components=component_idx)
for ch_type, ratio in ratios.items():
var_explained.loc[component_idx, ch_type] = ratio

var_explained
``````

Produces this output:

Best wishes,
Richard

1 Like

Wow, thank you so much, this works perfectly :)!
Best wishes,
M

1 Like