-
Notifications
You must be signed in to change notification settings - Fork 185
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
Within Session splitter #664
Open
brunaafl
wants to merge
78
commits into
NeuroTechX:develop
Choose a base branch
from
brunaafl:within_session
base: develop
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 57 commits
Commits
Show all changes
78 commits
Select commit
Hold shift + click to select a range
bacedc5
Creating new splitters and base evaluation
brunaafl 419b2ca
Adding metasplitters
brunaafl d6e795d
Fixing LazyEvaluation
brunaafl 140670c
Merge branch 'NeuroTechX:develop' into eval_splitters
brunaafl d724674
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] a278026
More optimized version of TimeSeriesSplit
brunaafl 300a6b9
More optimized version of TimeSeriesSplit
brunaafl 7cb79f6
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 55db70f
Addressing some comments: documentation, types, inconsistencies
brunaafl 2851a15
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] c73dd1a
Addressing some comments: optimizing code, adjusts
brunaafl 2b0e735
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] cf4b709
Adding examples
brunaafl 177bf65
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] a6b5772
Adding: Pytests for evaluation splitters, and examples for meta split…
brunaafl 26b13d5
Changing: name of TimeSeriesSplit to PseudoOnlineSplit
brunaafl e6661c4
Merge branch 'develop' into eval_splitters
brunaafl 430e3a8
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 698e539
Fixing pre-commit
brunaafl 0fff053
Merge remote-tracking branch 'origin/eval_splitters' into eval_splitters
brunaafl 98d12ac
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 558d27b
Adding some tests for metasplitters
brunaafl 34ea645
Merge remote-tracking branch 'origin/eval_splitters' into eval_splitters
brunaafl b435bf8
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] d8f26a3
Fixing pre-commit
brunaafl eaf0fb9
Merge remote-tracking branch 'origin/eval_splitters' into eval_splitters
brunaafl e5159f2
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 516a5e8
Fixing pre-commit
brunaafl b29ecd2
Merge remote-tracking branch 'origin/eval_splitters' into eval_splitters
brunaafl 37cff03
Fix example SamplerSplit
brunaafl 88ee910
Add shuffle and random_state parameters to WithinSession
brunaafl ea9cc59
Change nomenclature of variables
brunaafl 819c4ff
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 65c305e
Merge branch 'develop' into within_session
bruAristimunha f1ad587
FIX: fixing the whats_new.rst file
bruAristimunha 485e7a5
EHN: playing a little
bruAristimunha 3f3742f
FIX: fixing the import and docs/docstring
bruAristimunha c181c59
FIX: fixing the import and docs/docstring
bruAristimunha 8f034c8
FIX: fixing the import and docs/docstring
bruAristimunha fbef726
FIX: removing cross-session and cross-subject
bruAristimunha 837c061
FIX: focus only in the within-session
bruAristimunha 34822e9
Merge branch 'develop' into within_session
bruAristimunha 39e92e5
Fix test
brunaafl 612c6a6
Merge remote-tracking branch 'origin/within_session' into within_session
brunaafl 590edb1
[FIX] I think it is fixed.
bruAristimunha b151d61
[FIX] shuffle everything
bruAristimunha 602ccd5
Merge remote-tracking branch 'origin/within_session' into within_session
brunaafl 74cf246
Changing WithinSession image
brunaafl c85928d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] f3020ee
Update moabb/evaluations/splitters.py
brunaafl c628fd7
Update moabb/evaluations/splitters.py
brunaafl 83e425f
Update moabb/evaluations/splitters.py
brunaafl a785ef7
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 686572e
Merge branch 'develop' into within_session
bruAristimunha 8f8ada9
Adding possibility of passing a specific cv to do inner cv
brunaafl b87cf25
Merge remote-tracking branch 'origin/within_session' into within_session
brunaafl 42e6b7b
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] f66878a
Changing metasplitter behaviour to have the same behavior as other cr…
brunaafl 71cebb1
Merge remote-tracking branch 'origin/within_session' into within_session
brunaafl a948175
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] e276a32
Wrapper of KFold to instantiate a different cv for each group (subjec…
brunaafl feebe7d
Merge remote-tracking branch 'origin/within_session' into within_session
brunaafl ee584ef
Merge branch 'develop' into within_session
bruAristimunha 65bcf38
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 5a77a39
[FIX] pre-commit
bruAristimunha ef833f3
rename to rng
bruAristimunha 5f7511f
Delete misplaced image
brunaafl 634a4ee
Merge remote-tracking branch 'origin/within_session' into within_session
brunaafl bc65d20
remove repet img
bruAristimunha a1ca06f
Merge remote-tracking branch 'origin/within_session' into within_session
brunaafl 410b462
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 00f5ee8
[FIX] fix the splitter
bruAristimunha cfbbb52
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 26d7378
[EHN] debuging a little
bruAristimunha f73fd5d
[EHN] fixing the test with Bruna
bruAristimunha 09f3e3f
[EHN] removing pseudo-online as requested
bruAristimunha 9352a6e
[EHN] removing pseudo-online as requested
bruAristimunha 238f90a
[EHN] removing pseudo-online as requested
bruAristimunha 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
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
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
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. why not using only the other version? |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
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
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,87 @@ | ||
from sklearn.model_selection import BaseCrossValidator | ||
|
||
from moabb.evaluations.utils import sort_group | ||
|
||
|
||
class PseudoOnlineSplit(BaseCrossValidator): | ||
"""Pseudo-online split for evaluation test data. | ||
|
||
It takes into account the time sequence for obtaining the test data, and uses first run, | ||
or first #calib_size trials as calibration data, and the rest as evaluation data. | ||
Calibration data is important in the context where data alignment or filtering is used on | ||
training data. | ||
|
||
OBS: Be careful! Since this inference split is based on time disposition of obtained data, | ||
if your data is not organized by time, but by other parameter, such as class, you may want to | ||
be extra careful when using this split. | ||
|
||
Parameters | ||
---------- | ||
calib_size: int | ||
Size of calibration set, used if there is just one run. | ||
|
||
Examples | ||
-------- | ||
>>> import numpy as np | ||
>>> import pandas as pd | ||
>>> from moabb.evaluations.splitters import WithinSessionSplitter | ||
>>> from moabb.evaluations.metasplitters import PseudoOnlineSplit | ||
>>> X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [8, 9], [5, 4], [2, 5], [1, 7]]) | ||
>>> y = np.array([1, 2, 1, 2, 1, 2, 1, 2]) | ||
>>> subjects = np.array([1, 1, 1, 1, 1, 1, 1, 1]) | ||
>>> sessions = np.array([0, 0, 0, 0, 1, 1, 1, 1]) | ||
>>> runs = np.array(['0', '0', '1', '1', '0', '0', '1', '1']) | ||
>>> metadata = pd.DataFrame(data={'subject': subjects, 'session': sessions, 'run':runs}) | ||
>>> posplit = PseudoOnlineSplit | ||
>>> csubj = WithinSessionSplitter(cv=posplit, calib_size=1, custom_cv=True) | ||
>>> posplit.get_n_splits(metadata) | ||
2 | ||
>>> for i, (train_index, test_index) in enumerate(csubj.split(y, metadata)): | ||
>>> print(f"Fold {i}:") | ||
>>> print(f" Calibration: index={train_index}, group={subjects[train_index]}, sessions={sessions[train_index]}, runs={runs[train_index]}") | ||
>>> print(f" Test: index={test_index}, group={subjects[test_index]}, sessions={sessions[test_index]}, runs={runs[test_index]}") | ||
|
||
Fold 0: | ||
Calibration: index=[6, 7], group=[1 1], sessions=[1 1], runs=['1' '1'] | ||
Test: index=[4, 5], group=[1 1], sessions=[1 1], runs=['0' '0'] | ||
Fold 1: | ||
Calibration: index=[2, 3], group=[1 1], sessions=[0 0], runs=['1' '1'] | ||
Test: index=[0, 1], group=[1 1], sessions=[0 0], runs=['0' '0'] | ||
""" | ||
|
||
def __init__(self, calib_size: int = None): | ||
self.calib_size = calib_size | ||
|
||
def get_n_splits(self, metadata): | ||
return len(metadata.groupby(["subject", "session"])) | ||
|
||
def split(self, indices, y, metadata=None): | ||
|
||
if metadata is not None: | ||
for _, group in metadata.groupby(["subject", "session"]): | ||
runs = group.run.unique() | ||
if len(runs) > 1: | ||
brunaafl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
# To guarantee that the runs are on the right order | ||
runs = sort_group(runs) | ||
for run in runs: | ||
test_ix = group[group["run"] != run].index | ||
calib_ix = group[group["run"] == run].index | ||
yield list(test_ix), list(calib_ix) | ||
break # Take the fist run as calibration | ||
else: | ||
if self.calib_size is None: | ||
raise ValueError( | ||
"Data contains just one run. Need to provide calibration size." | ||
) | ||
# Take first #calib_size samples as calibration | ||
calib_size = self.calib_size | ||
calib_ix = group[:calib_size].index | ||
test_ix = group[calib_size:].index | ||
brunaafl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
yield list(calib_ix), list(test_ix) | ||
|
||
else: | ||
brunaafl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if self.calib_size is None: | ||
raise ValueError("Need to provide calibration size.") | ||
calib_size = self.calib_size | ||
yield list(indices[:calib_size]), list(indices[calib_size:]) |
tomMoral marked this conversation as resolved.
Show resolved
Hide resolved
|
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,133 @@ | ||
|
||
from sklearn.model_selection import BaseCrossValidator, StratifiedKFold | ||
from sklearn.utils import check_random_state | ||
|
||
from moabb.evaluations.metasplitters import PseudoOnlineSplit | ||
|
||
|
||
class WithinSessionSplitter(BaseCrossValidator): | ||
"""Data splitter for within session evaluation. | ||
|
||
Within-session evaluation uses k-fold cross_validation to determine train | ||
and test sets for each subject in each session. This splitter | ||
assumes that all data from all subjects is already known and loaded. | ||
|
||
.. image:: images/withinsess.png | ||
:alt: The schematic diagram of the WithinSession split | ||
:align: center | ||
|
||
|
||
Parameters | ||
---------- | ||
n_folds : int | ||
Number of folds. Must be at least 2. If | ||
random_state: int, RandomState instance or None, default=None | ||
Controls the randomness of splits. Only used when `shuffle` is True. | ||
Pass an int for reproducible output across multiple function calls. | ||
shuffle : bool, default=True | ||
Whether to shuffle each class's samples before splitting into batches. | ||
Note that the samples within each split will not be shuffled. | ||
custom_cv: bool, default=False | ||
Indicates if you are using PseudoOnlineSplit as cv strategy | ||
calib_size: int, default=None | ||
Size of calibration set if custom_cv==True | ||
cv: cros-validation object, default=StratifiedKFold | ||
Inner cross-validation strategy for splitting the sessions. Be careful, if | ||
PseudoOnlineSplit is used, it will return calibration and test indexes. | ||
|
||
|
||
Examples | ||
----------- | ||
|
||
>>> import pandas as pd | ||
>>> import numpy as np | ||
>>> from moabb.evaluations.splitters import WithinSessionSplitter | ||
>>> X = np.array([[1, 2], [3, 4], [5, 6], [1,4], [7, 4], [5, 8], [0,3], [2,4]]) | ||
>>> y = np.array([1, 2, 1, 2, 1, 2, 1, 2]) | ||
>>> subjects = np.array([1, 1, 1, 1, 1, 1, 1, 1]) | ||
>>> sessions = np.array(['T', 'T', 'T', 'T', 'E', 'E', 'E', 'E']) | ||
>>> metadata = pd.DataFrame(data={'subject': subjects, 'session': sessions}) | ||
>>> csess = WithinSessionSplitter(n_folds=2) | ||
>>> csess.get_n_splits(metadata) | ||
4 | ||
>>> for i, (train_index, test_index) in enumerate(csess.split(y, metadata)): | ||
... print(f"Fold {i}:") | ||
... print(f" Train: index={train_index}, group={subjects[train_index]}, session={sessions[train_index]}") | ||
... print(f" Test: index={test_index}, group={subjects[test_index]}, sessions={sessions[test_index]}") | ||
Fold 0: | ||
Train: index=[4 7], group=[1 1], session=['E' 'E'] | ||
Test: index=[5 6], group=[1 1], sessions=['E' 'E'] | ||
Fold 1: | ||
Train: index=[5 6], group=[1 1], session=['E' 'E'] | ||
Test: index=[4 7], group=[1 1], sessions=['E' 'E'] | ||
Fold 2: | ||
Train: index=[2 3], group=[1 1], session=['T' 'T'] | ||
Test: index=[0 1], group=[1 1], sessions=['T' 'T'] | ||
Fold 3: | ||
Train: index=[0 1], group=[1 1], session=['T' 'T'] | ||
Test: index=[2 3], group=[1 1], sessions=['T' 'T'] | ||
""" | ||
|
||
def __init__( | ||
self, | ||
cv=StratifiedKFold, | ||
bruAristimunha marked this conversation as resolved.
Show resolved
Hide resolved
|
||
custom_cv=False, | ||
n_folds: int = 5, | ||
random_state: int = 42, | ||
shuffle: bool = True, | ||
calib_size: int = None, | ||
): | ||
self.n_folds = n_folds | ||
self.shuffle = shuffle | ||
self.random_state = check_random_state(random_state) if shuffle else None | ||
self.cv = cv | ||
self.calib_size = calib_size | ||
self.custom_cv = custom_cv | ||
|
||
def get_n_splits(self, metadata): | ||
num_sessions_subjects = metadata.groupby(["subject", "session"]).ngroups | ||
return ( | ||
self.cv.get_n_splits(metadata) | ||
if self.custom_cv | ||
else self.n_folds * num_sessions_subjects | ||
) | ||
|
||
def split(self, y, metadata, **kwargs): | ||
all_index = metadata.index.values | ||
subjects = metadata["subject"].unique() | ||
|
||
# Shuffle subjects if required | ||
if self.shuffle: | ||
self.random_state.shuffle(subjects) | ||
|
||
for i, subject in enumerate(subjects): | ||
subject_mask = metadata.subject == subject | ||
subject_indices = all_index[subject_mask] | ||
subject_metadata = metadata[subject_mask] | ||
sessions = subject_metadata.session.unique() | ||
|
||
# Shuffle sessions if required | ||
if self.shuffle: | ||
self.random_state.shuffle(sessions) | ||
|
||
for j, session in enumerate(sessions): | ||
session_mask = subject_metadata.session == session | ||
indices = subject_indices[session_mask] | ||
group_y = y[indices] | ||
|
||
# Handle custom splitter | ||
if isinstance(self.cv(), PseudoOnlineSplit): | ||
splitter = self.cv(calib_size=self.calib_size) | ||
for calib_ix, test_ix in splitter.split( | ||
indices, group_y, subject_metadata[session_mask] | ||
): | ||
yield calib_ix, test_ix | ||
brunaafl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
else: | ||
# Handle standard CV like StratifiedKFold | ||
splitter = self.cv( | ||
n_splits=self.n_folds, | ||
shuffle=self.shuffle, | ||
random_state=self.random_state.randint(0, 2**10), | ||
) | ||
for train_ix, test_ix in splitter.split(indices, group_y): | ||
yield indices[train_ix], indices[test_ix] |
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
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,58 @@ | ||
import numpy as np | ||
import pytest | ||
from sklearn.model_selection import StratifiedKFold | ||
from sklearn.utils import check_random_state | ||
|
||
from moabb.datasets.fake import FakeDataset | ||
from moabb.evaluations.splitters import WithinSessionSplitter | ||
from moabb.paradigms.motor_imagery import FakeImageryParadigm | ||
|
||
|
||
dataset = FakeDataset(["left_hand", "right_hand"], n_subjects=3, seed=12) | ||
paradigm = FakeImageryParadigm() | ||
|
||
|
||
# Split done for the Within Session evaluation | ||
def eval_split_within_session(shuffle, random_state): | ||
random_state = check_random_state(random_state) if shuffle else None | ||
for subject in dataset.subject_list: | ||
X, y, metadata = paradigm.get_data(dataset=dataset, subjects=[subject]) | ||
sessions = metadata.session | ||
for session in np.unique(sessions): | ||
ix = sessions == session | ||
cv = StratifiedKFold(n_splits=5, shuffle=shuffle, random_state=random_state) | ||
X_, metadata_, y_ = X[ix], y[ix], metadata[ix] | ||
for train, test in cv.split(y_, metadata_): | ||
yield X_[train], X_[test] | ||
|
||
|
||
@pytest.mark.parametrize("shuffle", [True, False]) | ||
@pytest.mark.parametrize("random_state", [0, 42]) | ||
def test_within_session(shuffle, random_state): | ||
X, y, metadata = paradigm.get_data(dataset=dataset) | ||
bruAristimunha marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
split = WithinSessionSplitter(n_folds=5, shuffle=shuffle, random_state=random_state) | ||
|
||
for (X_train_t, X_test_t), (train, test) in zip( | ||
eval_split_within_session(shuffle=shuffle, random_state=random_state), | ||
split.split(y, metadata), | ||
): | ||
X_train, X_test = X[train], X[test] | ||
|
||
# Check if the output is the same as the input | ||
assert np.array_equal(X_train, X_train_t) | ||
assert np.array_equal(X_test, X_test_t) | ||
|
||
|
||
def test_is_shuffling(): | ||
X, y, metadata = paradigm.get_data(dataset=dataset) | ||
|
||
split = WithinSessionSplitter(n_folds=5, shuffle=False) | ||
split_shuffle = WithinSessionSplitter(n_folds=5, shuffle=True, random_state=3) | ||
|
||
for (train, test), (train_shuffle, test_shuffle) in zip( | ||
split.split(y, metadata), split_shuffle.split(y, metadata) | ||
): | ||
# Check if the output is the same as the input | ||
assert np.array_equal(train, train_shuffle) == False | ||
assert np.array_equal(test, test_shuffle) == False |
Oops, something went wrong.
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.
better represent only one session @brunaafl