Skip to content

WIP: Improve ica docstring, the second - #5620

Merged
cbrnr merged 7 commits into
mne-tools:masterfrom
jeythekey:improve-ICA-docstring-II
Nov 6, 2018
Merged

cbrnr merged 7 commits into
mne-tools:masterfrom
jeythekey:improve-ICA-docstring-II

Conversation

@jeythekey

Copy link
Copy Markdown
Contributor

One more attempt to make the docstring of ICA more explicit, especially as to the three different *_components_* parameters.

Also fixing wrong shape specifications of the attributes pca_components_ and pca_explained_variance_.

Reference issue

Expanding on #5114, in reference to #4856.

What does this implement/fix?

V.s.; in detail:

  • Adding a (first attempt of an) introduction about pre-ICA PCA, also referencing the warning about dimensionality reduction mentioned e.g. here.
    !! The formulation about the whitening needs to be reviewed, I am not sure, if this is correct! See below.
  • Referencing the most important methods which make use of the various attributes and parameters, especially thereby trying to be more explicit in which steps the various component-parameters are used.
  • Some re-formulations.
  • Mentioning Evoked as supported container.

OPEN QUESTIONS:

  1. max_pca_components:
    I am not sure if (with now explicitly specifying the sklearn.PCA svd_solver to 'full' as of sklearn 0.18.) max_pca_components has any influence on the actual PCA (e.g. by influencing the choice of the algorithm used; I am referring to this of the PCA docstring: "If n_components == 'mle' and svd_solver == 'full', Minka's MLE is used to guess the dimension.")
    If this would not be the case, the only other use case I could think of for including 2 separate n-PCA-parameters for decomp and re-comp is that the user makes up his mind later, after fitting, about how many PCA-compos to include in the reconstruction. But would it then hurt (data size etc.) to always return and store simply all PCA-compos?
    If the latter would also not be the case, I think this parameter is completely redundant and should be merged with n_pca_components (which has to be >= n_components_), as it is probably the primary source of confusion to have two parameters related to the number of PCA components.
    --> Could someone check this?

  2. I am not sure about the whitening/sphering:
    In _fit(), the variance-normalization is somehow applied to both the pca_components_ and the (un)mixing_matrix_ (once * and once /, though):

    593: self.pca_components_ *= np.sqrt(exp_var[:, None])  # (or in pca.fit_transform())
    ...
    619: self.unmixing_matrix_ /= np.sqrt(exp_var[sel])[None, :]  # whitening
    620: self.mixing_matrix_ = linalg.pinv(self.unmixing_matrix_)

Then, later in _pick_sources, the two are combined:

    unmixing = np.eye(_n_pca_comp)
    unmixing[:n_components, :n_components] = self.unmixing_matrix_
    unmixing = np.dot(unmixing, self.pca_components_[:_n_pca_comp])

So, I wonder, if it is correct to say that the (un)mixing_ matrix is whitened? Or would you rather way it is "also whitening the data"?
And could I think of applying the normalization in this way is in the end cancelling itself out when pca-unmixing and and ica-unmixing are being combined (i.e. in the complete unmixing)?

This is actually my first commit/PR ever, so please bear with me ;)

Trying to incorporate some comments from various discussions.
Mentioning fit() method.
@jeythekey jeythekey changed the title Improve ica docstring ii Improve ica docstring, the second Oct 17, 2018
jeythekey referenced this pull request Oct 17, 2018
* Docstring cosmetics; rename _pre_whitener to pre_whitener_

* Add pre_whitener_ to list of attributes

* Rename all _pre_whitener -> pre_whitener_

* Update tests

* Fix Python 2 encoding issue

* Unicode str for Python 2

* Cleanup and add shapes

* Escape training underscores

* Try single backticks

* dimension -> dimensionality

* Move Picard comment to Notes section, remove refs to non-existing methods
@larsoner

Copy link
Copy Markdown
Member

@cbrnr can you take a look?

@sappelhoff sappelhoff left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for adding documentation @jeythekey ... I read it and added some comments. My main point of confusion lies with the n_components with or without trailing _ ... perhaps the documentation could be improved even more in that regard.

Comment thread mne/preprocessing/ica.py Outdated
scaled to unit variance, also called sphering transformation) by means of
a Principle Component Analysis (PCA). This step additionally introduces the
option to reduce the dimensionality of the data prior to fitting/reverting
the ICA,controllable by the two parameters `max_pca_components` (for

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add space after ICA,

Comment thread mne/preprocessing/ica.py Outdated
On the other hand, for rank-deficient data such as EEG data after
average reference, it is recommended to reduce dimensionality by 1
for the ICA to work optimally.
See here: https://sccn.ucsd.edu/wiki/Chapter_09:_Decomposing_Data_Using_ICA#Issue:_ICA_returns_near-identical_components_with_opposite_polarities

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add the link to sccn as a proper reference under

References
--------------

Comment thread mne/preprocessing/ica.py Outdated
.. note:: Commonly used for reasons of i) computational efficiency and
ii) additional noise reduction, it is a matter of current debate
whether pre-ICA dimensionality reduction could decrease reliability/
stability of ICA, especially during preprocessing (see e.g. [5]).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

change to ... decrease the reliability ... [5]

(add "the", remove "/stability", remove (see e.g. ...) and just reference directly)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @sappelhoff for all the suggestions. I was trying to incorporate them. I left both reliability and stability since the paper describes (at least) two different issues with dim-reduction, one being test-retest-stability and the other being inter-subject consistency of components and number of clearly localizable dipolar components (the latter I summarize by "reliability").

Comment thread mne/preprocessing/ica.py Outdated
cumulative percentage of explained variance.
The number of PCA components from the pre-ICA PCA entering the ICA
decomposition in the `fit()` method.
If int, it must be <= `max_pca_components`.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If int, must be ...
(remove it)

Comment thread mne/preprocessing/ica.py Outdated
for re-projecting the data into sensor space, additinally controllable
by the `n_pca_components` parameter. It potentially [TO CHECK]
also influences the choice of the actual PCA-algorithm used. Refer to the
docstring of sklearn.PCA() for details.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you going to check this or are you asking somebody to do it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As mentioned in the PR description, it would be great if someone with some more serious background than me would check this. From what I understand, it does not (any more) and the parameter could be removed completely, resp. merged with n_pca_components. But I would not rely on this.

* Explaining the meaning of the trailing '_'
* Trying to make some formulations more explicit and consistent.
@codecov

codecov Bot commented Oct 17, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #5620 into master will increase coverage by 0.06%.
The diff coverage is 100%.

@@            Coverage Diff             @@
##           master    #5620      +/-   ##
==========================================
+ Coverage   88.44%   88.51%   +0.06%     
==========================================
  Files         363      369       +6     
  Lines       68211    69136     +925     
  Branches    11526    11645     +119     
==========================================
+ Hits        60327    61193     +866     
- Misses       5043     5089      +46     
- Partials     2841     2854      +13

Comment thread mne/preprocessing/ica.py Outdated
.. note:: Commonly used for reasons of i) computational efficiency and
ii) additional noise reduction, it is a matter of current debate
whether pre-ICA dimensionality reduction could decrease the reliability
and stability of the ICA, at least for EEG data and especially during

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be great to get a comment by e.g. @agramfort on this issue, since the paper referenced only talks about 72-channel EEG data. I could well imagine, that for >260 channels, redundancy/rank deficiency (?) could arise and dimensionality reduction again increase ICA reliability/stability. (At least I get convergence problems if including all MEG channels.)
Maybe there is a way to empirically estimate the rank of the data a priori and base the decision about the dimensionality reduction on this?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIRC the [5] paper does not show reduction in ICA reliability if one chooses to keep PCA components explaining 95% of the variance, only going below 95% is detrimental, right? If so - you could add a note about this here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, they are saying you shouldn't do it at all: "PCA rank reduction (even if removing only 1% of data variance) adversely affected the dipolarity and stability of ICs accounting for potentials arising from brain and known non-brain processes."

But it is true that they only used 72 channel data, although I'm pretty sure their finding generalizes to more channels. The problem is that physiological sources might be very low variance, and thus PCA reduction might get rid of these sources.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my take on this is that at least part of their argument is flawed as initialisation of ICA solvers when you don't use PCA gives you already super dipolar components. See https://hal.archives-ouvertes.fr/hal-01451432

a second order consequence is that you should not use infomax or extended-infomax as such solvers suffer from convergence issues. This is the problem we aimed to address with Picard https://github.com/pierreablin/picard . As Picard and Infomax solve exactly the same maximum likelihood problem, if you don't get the same result as with infomax it must be a convergence issue of the solver of infomax.

cc @pierreablin

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cbrnr Ok, I take that 95% back, but 99% doesn't look so bad in the figures. And it depends on your use case - if you care only about removal of artifactual activity with ICA (this is what I almost always do) then the fact that you get less dipolar brain sources is not so relevant (at least to the extent that it does not influence artifact cleaning).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I always mix up sphering and whitening. (Say it with me: Both sphering and PCA are whitening transforms.) Very nice paper too - I think I'll take a closer look at Picard for my next EEG analysis.

Are you planning to address this flaw with a rebuttal? It would be nice to read some kind of published document, because EEGLAB-related stuff by these authors tend to be very visible in the community.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know but my time is too limited to start this. First we would need to replicate the study and show that using PCA full rank (and not sphering) breaks the conclusions. Too many stuff on my plate already.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can relate 😄 - but you already have the preprint out there, which I really like. One quick question: LBFGS is improving the ICA results by pushing the convergence. This is what EEGLAB folks are doing with AMICA, where they combine gradient descent and quasi-Newton optimization. Is this available somewhere within MNE? Is this what Picard does?

@agramfort agramfort Oct 30, 2018 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AMICA uses a quasi Newton with Hessian approximation (which is not perfect) and what Picard does is using L-BFGS to correct the rough Hessian approximation. Now AMICA does more. It estimates the density distribution of the sources while Picard uses the same fixed non-linearities/densities as Infomax. Also AMICA does some unclear magic to omit outlier samples during the estimation. It is still unclear if AMICA is considered better than Infomax because 1) it estimates the densities 2) uses quasi Newton or 3) is robust to artifacts.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR is a bit weird place to continue this discussion (if you want we could continue over email), but I thought a bit more about your comments @agramfort. Since the terms kept confusing me, I found that what you are referring to as sphering is more commonly called ZCA. Thus, de-correlating data is called whitening or sphering (these terms can be used interchangeably). One specific method to whiten is PCA. Another method is ZCA. These two methods are related in a sense that ZCA is PCA followed by a rotation back. This SO answer summarizes this nicely.

I will think more on the implications of these two methods for the initialization of ICA. Let me know if and how you would like to continue this discussion.

@cbrnr

cbrnr commented Oct 18, 2018

Copy link
Copy Markdown
Contributor

I'll take a look soonish.

@agramfort

Copy link
Copy Markdown
Member

@cbrnr can you have a look?

Comment thread mne/preprocessing/ica.py Outdated
and stability of the ICA, at least for EEG data and especially during
preprocessing [5].
On the other hand, for rank-deficient data such as EEG data after
average reference, it is recommended to reduce the dimensionality by 1

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe something like:

Suggested change
average reference, it is recommended to reduce the dimensionality by 1
average reference or interpolation, it is recommended to reduce
the dimensionality (by 1 for average reference and 1 for each
interpolated channel) for optimal ICA performance [6].

@agramfort

Copy link
Copy Markdown
Member

@mmagnuski @cbrnr push directly to this branch to speed things up if you have a bit of time.

Comment thread mne/preprocessing/ica.py Resolved
Comment thread mne/preprocessing/ica.py Outdated
used for re-projecting the data into sensor space, additionally
controllable by the `n_pca_components` parameter. It potentially [TO
CHECK] also influences the choice of the actual PCA-algorithm used.
Refer to the docstring of sklearn.PCA() for details.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We explicitly call PCA with solver='full', so I think the choice of the actual PCA algorithm is fixed to the standard full one.

Comment thread mne/preprocessing/ica.py Outdated
be used. If float between 0 and 1, components will be selected by the
cumulative percentage of explained variance.
Controls the number of PCA components from the pre-ICA PCA entering the
ICA decomposition in the `fit()` method.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the convention is to write ... in the fit method ... (without the parens). There are several occurrences of this in the text.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One option would be to link with

:meth:`ICA.fit`

Or maybe even this would work (you can test locally with make html_dev-noplot in the doc/ directory)

:meth:`fit`

@cbrnr

cbrnr commented Oct 30, 2018

Copy link
Copy Markdown
Contributor

The ICA parameters still confuse the hell out of me, but I think the changes in this PR definitely improve things. It would be great if we could then continue our discussion in #4856 - for example, if n_pca_components is really only used in the apply method, then why don't we remove this parameter completely from __init__ and move it to the apply method instead?

@larsoner larsoner added this to the 0.18 milestone Nov 3, 2018
@agramfort

agramfort commented Nov 3, 2018 via email

Copy link
Copy Markdown
Member

Comment thread mne/preprocessing/ica.py Outdated
prior to fitting the ICA and prior to reverting to sensor space,
controllable by the two parameters `max_pca_components` and
`n_pca_components`, respectively.
.. note:: Commonly used for reasons of i) computational efficiency and

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread mne/preprocessing/ica.py Outdated
especially during preprocessing [5].
On the other hand, for rank-deficient data such as EEG data after
average reference or interpolation, it is recommended to reduce
the dimensionality by 1 for optimal ICA performance [6].

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is all too long for this section. Let's move it to the Notes section. The "Caveat!" should perhaps go with it. Also, [6]_.

Comment thread mne/preprocessing/ica.py Outdated
ii) additional noise reduction, it is a matter of current debate
whether pre-ICA dimensionality reduction could decrease the
reliability and stability of the ICA, at least for EEG data and
especially during preprocessing [5].

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[5]_

Comment thread mne/preprocessing/ica.py Outdated
be used. If float between 0 and 1, components will be selected by the
cumulative percentage of explained variance.
Controls the number of PCA components from the pre-ICA PCA entering the
ICA decomposition in the `fit()` method.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One option would be to link with

:meth:`ICA.fit`

Or maybe even this would work (you can test locally with make html_dev-noplot in the doc/ directory)

:meth:`fit`

Comment thread mne/preprocessing/ica.py Outdated
If int, must be <= `max_pca_components`.
If float between 0 and 1, the number of components selected matches the
number of components with a cumulative explained variance below
`n_components` (<1> resulting in `max_pca_components`).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

<1>? I don't think we have ever used this notation, you can just do "1 resulting in" or "a value of 1 resulting in"

Comment thread mne/preprocessing/ica.py Outdated
parameter in the `fit()` method is stored in the attribute
`n_components_`.
(Note that the trailing ``_`` signifies attributes added to the object
by methods to store results from the actual calculations.)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Super long docstrings hurt readability. Let's move this _-related note to the Notes section. It's a general point anyway.

Comment thread mne/preprocessing/ica.py Outdated
NeuroImage 175, pp.176–187.
https://sccn.ucsd.edu/%7Earno/mypapers/Artoni2018.pdf

.. [6] https://sccn.ucsd.edu/wiki/Chapter_09:_Decomposing_Data_Using_ICA#Issue:_ICA_returns_near-identical_components_with_opposite_polarities # noqa

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

URLs should not go in References but be standard RST links like:

... see the `decomp site <ucsd_site_>`_.

.. _ucsd_site: https://blahblah

See for example how we do it here:

https://github.com/mne-tools/mne-python/pull/5692/files#diff-2b866ae21caee8720a60af18064ddf89R9

@larsoner larsoner modified the milestones: 0.18, 0.17 Nov 3, 2018
@larsoner larsoner changed the title Improve ica docstring, the second WIP: Improve ica docstring, the second Nov 3, 2018
@cbrnr

cbrnr commented Nov 5, 2018

Copy link
Copy Markdown
Contributor

@agramfort sounds good 😃! Regarding this PR, I'm OK with merging once all comments have been addressed (@larsoner had quite a few). Then we can continue our quest of improving ICA documentation in #4856.

@larsoner

larsoner commented Nov 5, 2018

Copy link
Copy Markdown
Member

Pushed fixes. @cbrnr feel free to merge after one more look at the diff and/or CircleCI output if you are happy

@larsoner

larsoner commented Nov 5, 2018

Copy link
Copy Markdown
Member

@cbrnr
cbrnr merged commit cc3f02e into mne-tools:master Nov 6, 2018
@cbrnr

cbrnr commented Nov 6, 2018

Copy link
Copy Markdown
Contributor

OK - although I'm pretty sure the text (or rather, the parameters) is/are still confusing for someone who just wants to use ICA, it is definitely better than before. Let's keep working on it in #4856.

Thanks @jeythekey and @larsoner!

@larsoner

Copy link
Copy Markdown
Member

@jeythekey we don't have a proper name for you and we don't have a whats_new.rst for you -- let me know if you have a name and URL you want us to use

@jeythekey
jeythekey deleted the improve-ICA-docstring-II branch February 15, 2019 09:31
jeythekey added a commit to jeythekey/mne-python that referenced this pull request Apr 27, 2019
jeythekey added a commit to jeythekey/mne-python that referenced this pull request Apr 27, 2019
mmagnuski pushed a commit that referenced this pull request May 3, 2019
* Fix sorting in descending order in ica._detect_artifacts (was sortin in ascending order).

* Fix sfreq selection in ica._band_pass_filter (called (only) in ica.score_sources to filter sources and targets) to use the raw sfreq rather than the one used for fitting the ica.

* Incorporate missed suggestion from #5620 + summary of discussion

* fix PEP8

* fix typo in doc

* Allow both exclude and ica.exclude to be array_like by always converting to list first.

* ica.detect_artifacts: Corrected doc according to code and changed some default values to yield the same compos as before

* Added test for checking descending sorting in detect_artifacts for integer criterion

* Stylistic improvements thanks to jona-sassenhagen

* Fix test for score-sorting

* pep8 and whats_new.rst

* Remove links to privat funcs in whats_new.rst

* fix links in whats_new

* STY: No end period

* Futher improvements thanks to mmagnuski and a few further corrections in the docstrings of run_ica and detect_artifacts

* Added warning for new sorting-direction in detect_artifacts; added whats_new from #6247

* improve bug section; remove warning again; typo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants