-
Notifications
You must be signed in to change notification settings - Fork 41
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add first version of permutation interence method in the model_selection module. #136
Open
LegrandNico
wants to merge
1
commit into
jameschapman19:main
Choose a base branch
from
LegrandNico:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
from ._search import GridSearchCV, RandomizedSearchCV | ||
from ._permutation import permutation_test_score as permutation_test_score |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
import numpy as np | ||
from typing import Optional, Tuple, Dict | ||
from tqdm import tqdm | ||
from cca_zoo.models._cca_base import _CCA_Base | ||
|
||
|
||
def permutation_test_score( | ||
estimator: _CCA_Base, X: np.ndarray, Y: np.ndarray, latent_dims: int = 1, | ||
n_perms: int = 1000, Z: Optional[np.ndarray] = None, W: Optional[np.ndarray] = None, | ||
sel: Optional[np.ndarray] = None, partial: bool = True, | ||
parameters: Optional[Dict] = None | ||
) -> Tuple[float, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]: | ||
""" | ||
Permutation inference for canonical correlation analysis (CCA) _[1]. | ||
|
||
This code is adapted from the Matlab function accompagning the paper: | ||
https://github.com/andersonwinkler/PermCCA/blob/6098d35da79618588b8763c5b4a519438703dba4/permcca.m#L131-L164 | ||
|
||
Parameters | ||
---------- | ||
estimator : _CCA_Base | ||
The object to use to fit the data. This must be one of the CCA models from | ||
py:class:`cca_zoo-models` and implementing a `fit` method. | ||
Y : np.ndarray | ||
Left set of variables, size N by P. | ||
X : np.ndarray | ||
Right set of variables, size N by Q. | ||
latent_dims : int | ||
The number of latent dimensions infered during the model fitting. Defaults to | ||
`1`. | ||
n_perms : int | ||
An integer representing the number of permutations. Default is 1000 permutations. | ||
Z : np.ndarray | ||
(Optional) Nuisance variables for both (partial CCA) or left | ||
side (part CCA) only. | ||
W : np.ndarray | ||
(Optional) Nuisance variables for the right side only (bipartial CCA). | ||
sel : np.ndarray | ||
(Optional) Selection matrix or a selection vector, to use Theil's residuals | ||
instead of Huh-Jhun's projection. If specified as a vector, it can be made | ||
of integer indices or logicals. The R unselected rows of Z (S of W) must be full | ||
rank. Use -1 to randomly select N-R (or N-S) rows. | ||
partial : bool | ||
(Optional) Boolean indicating whether this is partial (true) or part (false) CCA. | ||
Default is true, i.e., partial CCA. | ||
parameters : dict | None | ||
(Optional) Any additional keyword arguments required by the given estimator. | ||
|
||
|
||
Returns | ||
------- | ||
p : float | ||
p-values, FWER corrected via closure. | ||
r : np.ndarray | ||
Canonical correlations. | ||
A : np.ndarray | ||
Canonical coefficients (X). | ||
B : np.ndarray | ||
Canonical coefficients (Y). | ||
U : np.ndarray | ||
Canonical variables (X). | ||
V : np.ndarray | ||
Canonical variables (Y). | ||
|
||
References | ||
---------- | ||
.. [1] Winkler AM, Renaud O, Smith SM, Nichols TE. Permutation Inference for | ||
Canonical Correlation Analysis. NeuroImage. 2020; 117065. | ||
|
||
""" | ||
|
||
rng = np.random.RandomState(42) | ||
lW, cnt = np.zeros(latent_dims), np.zeros(latent_dims) | ||
n_obs = X.shape[0] | ||
if parameters is None: | ||
parameters = {} | ||
|
||
# Initial fit of the CCA model (without any permutation) | ||
init_model = estimator(latent_dims=(latent_dims), **parameters) | ||
init_model.fit((X, Y)) | ||
|
||
A, B = init_model.get_loadings((X, Y)) | ||
U, V = init_model.transform((X, Y)) | ||
|
||
for i in tqdm(range(n_perms)): | ||
|
||
# If user didn't supply a set of permutations, permute randomly both Y and X. | ||
# Otherwise, use the permtuation set to shuffle one side only. | ||
if i == 0: | ||
# First permutation is no permutation | ||
X_perm = X | ||
Y_perm = Y | ||
else: | ||
x_idx, y_idx = rng.permutation(n_obs), rng.permutation(n_obs) | ||
X_perm = X[x_idx] | ||
Y_perm = Y[y_idx] | ||
|
||
# For each canonical variable | ||
for k in range(latent_dims): | ||
|
||
# Fit the CCA model using the permuted datasets | ||
perm_model = estimator(latent_dims=(latent_dims - k), **parameters) | ||
perm_model.fit((X_perm[:, k:], Y_perm[:, k:])) | ||
|
||
# Estimate correlation coefficient for this CCA fit | ||
r_perm = perm_model.correlations((X_perm[:, k:], Y_perm[:, k:]))[0][1] | ||
|
||
lWtmp = -1 * np.cumsum(np.log(1 - r_perm ** 2)[::-1])[::-1] | ||
lW[k] = lWtmp[0] | ||
|
||
if i == 0: | ||
lw1 = lW | ||
cnt = cnt + (lW >= lw1) | ||
|
||
# compute p-values | ||
p = np.maximum.accumulate(cnt/n_perms) | ||
|
||
return p, A, B, U, V |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
from cca_zoo.model_selection import permutation_test_score | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Wonder if something like this might make a good test. |
||
from sklearn.utils.validation import check_random_state | ||
from cca_zoo.models import CCA | ||
|
||
n = 50 | ||
rng = check_random_state(0) | ||
X = rng.rand(n, 4) | ||
Y = rng.rand(n, 5) | ||
|
||
|
||
def test_permutation_test_score(): | ||
p, A, B, U, V = permutation_test_score(X=X, Y=Y, estimator=CCA, latent_dims=2) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Really nice work translating the matlab. I think I've found the sources of the bugs you mention. Take a look and see what you think.