Cross-Validation API¶
XDFlow validators run the evaluation loop. They build folds, apply split policies from named coordinates, reuse fold-invariant work, clone and refit stateful steps, score predictions, and keep outputs aligned with the source data.
Use these classes instead of handwritten sklearn split loops when validation depends on metadata, pipeline state, or reusable preprocessing.
For custom split policies, see Writing Custom Cross-Validators.
Base Validator¶
CrossValidator ¶
CrossValidator(pooling_score_weight: float = 0.0, use_stateful_fit_cache: bool = True, release_fold_memory: bool = False, scoring: str | Callable | None = None, scoring_needs_proba: bool = False, stratify_coord: str | None = None, exclude_intertrial_from_scoring: bool = False, exclude_offsets_from_scoring: bool = False, verbose: bool = True)
Bases: ABC
Base class for evaluating a predictive pipeline with held-out data.
A cross-validator owns the train/validation/holdout splitting strategy and
evaluates a complete Pipeline. Stateless pipeline steps can be run once
before fold splitting, while stateful steps are cloned and fitted on each
fold's training data. This keeps expensive deterministic preprocessing out
of the per-fold loop when possible.
Results are stored on the instance after evaluation, including fold scores,
out-of-fold predictions, optional probabilities, and holdout predictions.
Scorers may accept either (y_true, y_pred) or
(y_true, y_pred, container) when coordinate-aware scoring is needed.
Subclasses define only the split policy by implementing _split_holdout and
_get_splits.
Initialize scoring, caching, and split-independent CV options.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pooling_score_weight
|
float
|
Interpolation factor between the average fold score (0.0) and the pooled OOF score (1.0). Defaults to 0.0. Must be between 0.0 and 1.0. Higher values give more weight to folds with more trials. |
0.0
|
use_stateful_fit_cache
|
bool
|
Whether to cache stateful transforms during CV. |
True
|
release_fold_memory
|
bool
|
Whether to aggressively release per-fold objects and clear PyTorch CUDA caches after each fold. |
False
|
scoring
|
str | Callable | None
|
Metric name or callable. If None, classification defaults
to |
None
|
scoring_needs_proba
|
bool
|
Whether a custom scorer expects probabilities from predict_proba instead of hard predictions. |
False
|
exclude_intertrial_from_scoring
|
bool
|
If True, automatically remove any trials whose event_type coordinate is "intertrial" from CV/holdout scoring. |
False
|
exclude_offsets_from_scoring
|
bool
|
If True, remove trials whose time_offset_ms coordinate is not 0 from CV/holdout scoring. |
False
|
stratify_coord
|
str | None
|
Optional coordinate name to use for stratified splits. If set, holdout and CV splits will stratify on this coordinate (must be present in the data). For multi-target/regression tasks, this allows stratifying on a categorical coord such as stimulus. |
None
|
verbose
|
bool
|
Whether to print verbose output specific to the cross-validator. Verbosity of transforms is separetely controlled by class-level function arguments. |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If pooling_score_weight is not between 0.0 and 1.0 |
Source code in xdflow/cv/base.py
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | |
holdout_confusion_matrix_
property
¶
holdout_confusion_matrix_: ndarray
Calculate confusion matrix from holdout test predictions.
If a scoring mask has been set via compute_holdout_scoring_mask(), the confusion matrix will be computed only on the filtered samples, matching the scorer's logic.
Returns:
| Type | Description |
|---|---|
ndarray
|
Confusion matrix as numpy array |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no holdout predictions available or task is not classification |
holdout_confusion_matrix_normalized_
property
¶
holdout_confusion_matrix_normalized_: ndarray
Calculate normalized confusion matrix from holdout test predictions.
If a scoring mask has been set via compute_holdout_scoring_mask(), the confusion matrix will be computed only on the filtered samples, matching the scorer's logic.
Returns:
| Type | Description |
|---|---|
ndarray
|
Normalized confusion matrix as numpy array (rows sum to 1) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no holdout predictions available or task is not classification |
metric_name_
property
¶
metric_name_: str
Get the name of the scoring metric used for evaluation.
Returns:
| Type | Description |
|---|---|
str
|
Name of the metric (e.g., 'r2', 'mse', 'f1_weighted', 'custom') |
oof_score_
property
¶
oof_score_: float
Calculate the selected metric score from out-of-fold predictions.
Note: For scorers that require a container argument, OOF scoring is not possible since predictions come from multiple folds. In this case, returns the mean CV score as a fallback.
Returns:
| Type | Description |
|---|---|
float
|
Score calculated using the selected scoring function |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no out-of-fold predictions available |
mean_cv_score_
property
¶
mean_cv_score_: float
Get the mean cross-validation score across all folds.
Returns:
| Type | Description |
|---|---|
float
|
Mean of scores from all cross-validation folds |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no cross-validation scores available |
oof_f1_score_
property
¶
oof_f1_score_: float
Calculate F1 score from out-of-fold predictions.
Convenience property for classification tasks that always returns weighted F1 score, regardless of the configured scoring metric.
Returns:
| Type | Description |
|---|---|
float
|
Weighted F1 score across all out-of-fold predictions |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no out-of-fold predictions available |
holdout_f1_score_
property
¶
holdout_f1_score_: float
Calculate F1 score from holdout predictions.
Convenience property for classification tasks that always returns weighted F1 score, regardless of the configured scoring metric.
Returns:
| Type | Description |
|---|---|
float
|
Weighted F1 score from holdout predictions |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no holdout predictions available |
mean_cv_f1_score_
property
¶
mean_cv_f1_score_: float
Get the mean cross-validation F1 score across all folds.
Returns:
| Type | Description |
|---|---|
float
|
Mean of F1 scores from all cross-validation folds |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no cross-validation scores available |
oof_confusion_matrix_
property
¶
oof_confusion_matrix_: ndarray
Calculate confusion matrix from out-of-fold predictions.
Returns:
| Type | Description |
|---|---|
ndarray
|
Confusion matrix as numpy array |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no out-of-fold predictions available or task is not classification |
oof_confusion_matrix_normalized_
property
¶
oof_confusion_matrix_normalized_: ndarray
Calculate normalized confusion matrix from out-of-fold predictions.
Returns:
| Type | Description |
|---|---|
ndarray
|
Normalized confusion matrix as numpy array (rows sum to 1) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no out-of-fold predictions available or task is not classification |
score_
property
¶
score_: float
Calculate the final CV score based on the pooling_score_weight.
Blends the average fold score and pooled out-of-fold score using: score = (1 - pooling_score_weight) * mean_cv_f1_score_ + pooling_score_weight * oof_f1_score_
When pooling_score_weight = 0.0: Returns average fold score (standard behavior) When pooling_score_weight = 1.0: Returns pooled OOF score When pooling_score_weight = 0.5: Returns equal blend of both
Returns:
| Type | Description |
|---|---|
float
|
Final blended cross-validation score |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no cross-validation scores are available |
set_pipeline ¶
set_pipeline(pipeline: Pipeline)
Set the pipeline to be used for cross-validation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pipeline
|
Pipeline
|
Pipeline to be used for cross-validation |
required |
Source code in xdflow/cv/base.py
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 | |
cross_validate ¶
cross_validate(initial_container: DataContainer, verbose: bool = False, pruning_callback: Callable[[int, float], None] | None = None, **kwargs) -> float
Runs the full cross-validation process on the train and validation sets. Held out test set is not used here.
This method automatically detects stateless and stateful pipeline components and executes them optimally: stateless parts run once, stateful parts per fold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_container
|
DataContainer
|
Input DataContainer to cross-validate on |
required |
verbose
|
bool
|
Whether to enable verbose logging in transforms |
False
|
**kwargs
|
Additional arguments passed to splitting methods |
{}
|
Returns:
| Type | Description |
|---|---|
float
|
Mean cross-validation score |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no pipeline is assigned |
Source code in xdflow/cv/base.py
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 | |
finalize_pipeline ¶
finalize_pipeline(container: DataContainer, verbose: bool = False) -> Pipeline
Finalizes a model for production by fitting on the entire provided container.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
container
|
DataContainer
|
DataContainer to fit the final model on |
required |
verbose
|
bool
|
Whether to enable verbose logging in transforms |
False
|
Returns:
| Type | Description |
|---|---|
Pipeline
|
The fitted pipeline object, ready for inference. |
Source code in xdflow/cv/base.py
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 | |
score_on_holdout ¶
score_on_holdout(initial_container: DataContainer, verbose: bool = False) -> float
Performs the final evaluation on the held-out test set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_container
|
DataContainer
|
The original DataContainer used in cross_validate() |
required |
verbose
|
bool
|
Whether to enable verbose logging in transforms |
False
|
Returns:
| Type | Description |
|---|---|
float
|
Final holdout test score |
Raises:
| Type | Description |
|---|---|
ValueError
|
If holdout indices don't exist (cross_validate() not called first) |
Source code in xdflow/cv/base.py
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 | |
compute_holdout_scoring_mask ¶
compute_holdout_scoring_mask(mask_func: Callable[[DataContainer], ndarray]) -> np.ndarray
Compute and store the mask used by a container-aware scorer.
This method should be called after score_on_holdout() when using a custom container-aware scorer that filters samples. The mask will be used to generate filtered confusion matrices that match the scoring logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_func
|
Callable[[DataContainer], ndarray]
|
Function that takes a DataContainer and returns a boolean mask array. Should implement the same filtering logic as the custom scorer. Example: lambda c: (c.coords['concentration_bin'] == 'conc_2p4') |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The computed boolean mask array |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no holdout container is available, or if mask shape/dtype is invalid |
Example
cv.score_on_holdout(data_container) cv.compute_holdout_scoring_mask(lambda c: c.coords['concentration_bin'] == 'target') cm = cv.holdout_confusion_matrix_ # Now filtered to match scorer
Source code in xdflow/cv/base.py
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 | |
get_fold_scores ¶
get_fold_scores() -> list
Get individual fold scores.
Returns:
| Type | Description |
|---|---|
list
|
List of scores for each cross-validation fold |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no cross-validation scores available |
Source code in xdflow/cv/base.py
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 | |
get_holdout_container ¶
get_holdout_container(initial_container: DataContainer, *, verbose: bool = False) -> DataContainer
Return the holdout trials from the original data container.
This helper returns the raw-space slice referenced by holdout_trial_labels_.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_container
|
DataContainer
|
The original DataContainer provided to cross_validate()/score_on_holdout(). |
required |
verbose
|
bool
|
Whether to enable verbose logging in transforms. |
False
|
Returns:
| Type | Description |
|---|---|
DataContainer
|
DataContainer containing only the holdout trials in raw space. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no holdout data is available (e.g., test_size not set). |
Source code in xdflow/cv/base.py
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 | |
plot_confusion_matrix ¶
plot_confusion_matrix(use_holdout: bool = True, normalize: bool = True, title_info: str = '', **kwargs)
Plot the confusion matrix.
Note: Only works for classification tasks.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the pipeline is not a classifier |
Source code in xdflow/cv/base.py
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 | |
K-Fold Validators¶
KFoldValidator ¶
KFoldValidator(n_splits: int = 5, shuffle: bool = True, random_state: int = 0, test_size: float | None = None, pooling_score_weight: float = 0.0, scoring: str | Callable | None = None, stratify_coord: str | None = None, exclude_intertrial_from_scoring: bool = False, exclude_offsets_from_scoring: bool = False, use_stateful_fit_cache: bool = True, release_fold_memory: bool = False, scoring_needs_proba: bool = False, verbose: bool = True)
Bases: CrossValidator
Implements cross-validation using a stratified K-Fold strategy with optional holdout set.
This provides a concrete implementation of CrossValidator using scikit-learn's StratifiedKFold for balanced splits across classes.
Initialize KFold cross-validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_splits
|
int
|
Number of folds for cross-validation |
5
|
shuffle
|
bool
|
Whether to shuffle data before splitting |
True
|
random_state
|
int
|
Random seed for reproducibility |
0
|
test_size
|
float | None
|
Proportion of data to use as holdout test set (0.0-1.0). If None or 0, no holdout set is created. |
None
|
pooling_score_weight
|
float
|
Interpolation factor between the average fold score (0.0) and the pooled OOF score (1.0). Defaults to 0.0. |
0.0
|
scoring
|
str | Callable | None
|
Scoring metric to use. If None, auto-selects based on task type. |
None
|
stratify_coord
|
str | None
|
Optional coordinate name to use for stratified splits (train/val/holdout). |
None
|
exclude_intertrial_from_scoring
|
bool
|
Whether to drop intertrial segments when evaluating folds/holdout. |
False
|
use_stateful_fit_cache
|
bool
|
Whether to cache stateful transforms during CV. |
True
|
verbose
|
bool
|
Whether to print verbose output specific to cross-validation. |
True
|
Source code in xdflow/cv/kfold.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | |
GroupedKFoldValidator ¶
GroupedKFoldValidator(n_splits: int = 5, shuffle: bool = True, random_state: int = 0, test_size: float | None = None, pooling_score_weight: float = 0.0, group_coord: str | None = None, train_groups: list[Hashable] | Hashable | None = None, val_groups: list[Hashable] | Hashable | None = None, test_groups: list[Hashable] | Hashable | None = None, scoring: str | Callable | None = None, stratify_coord: str | None = None, stratify_by_group: bool = True, exclude_intertrial_from_scoring: bool = False, exclude_offsets_from_scoring: bool = False, use_stateful_fit_cache: bool = True, release_fold_memory: bool = False, scoring_needs_proba: bool = False, verbose: bool = True)
Bases: CrossValidator
Implements cross-validation using a stratified K-Fold strategy. Groups are specified by the group_coord parameter. K-folds are stratified by both the group and target coordinates. Specific groups can be specified for training, validation, and testing using the values of the group_coord coordinate. If no groups are specified, all groups are used for training/validation/testing.
E.g. if group_coord = 'animal', train_groups = None, val_groups = [35], and test_groups = [35], all data will be used for training, but only animal 35 will be used for validation and testing.
Useful for testing the performance of a model across different groups, especially for domain adaptation.
Initialize GroupedKFoldValidator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_splits
|
int
|
Number of folds for cross-validation |
5
|
shuffle
|
bool
|
Whether to shuffle data before splitting |
True
|
random_state
|
int
|
Random seed for reproducibility |
0
|
test_size
|
float | None
|
Proportion of data to use as holdout test set (0.0-1.0). If None or 0, no holdout set is created. |
None
|
pooling_score_weight
|
float
|
Interpolation factor between the average fold score (0.0) and the pooled OOF score (1.0). Defaults to 0.0. |
0.0
|
group_coord
|
str | None
|
Coordinate to group by. |
None
|
train_groups
|
list[Hashable] | Hashable | None
|
Groups to use for training. If None, all groups are used. |
None
|
val_groups
|
list[Hashable] | Hashable | None
|
Groups to use for validation. If None, all groups are used. |
None
|
test_groups
|
list[Hashable] | Hashable | None
|
Groups to use for testing. If None, all groups are used. |
None
|
scoring
|
str | Callable | None
|
Scoring metric to use. If None, auto-selects based on task type. |
None
|
stratify_coord
|
str | None
|
Optional coordinate name to use for stratified splits. |
None
|
stratify_by_group
|
bool
|
Whether to stratify splits by group coordinate in addition to target. If True (default), stratifies by group+target combination. If False, only stratifies by target (or stratify_coord if set). |
True
|
exclude_intertrial_from_scoring
|
bool
|
Whether to drop intertrial segments during evaluation. |
False
|
use_stateful_fit_cache
|
bool
|
Whether to cache stateful transforms during CV. |
True
|
verbose
|
bool
|
Whether to print verbose output specific to cross-validation. |
True
|
Source code in xdflow/cv/kfold.py
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 | |
Domain Sampling¶
SampledDomainKFoldValidator ¶
SampledDomainKFoldValidator(*, domain_coord: str, target_domains: list[Hashable] | Hashable, source_domains: list[Hashable] | Hashable | None = None, label_coord: str | None = None, label_sample_counts: Mapping[Hashable, int | None] | None = None, default_samples_per_label: int | None = None, n_splits: int = 5, shuffle: bool = True, random_state: int = 0, test_size: float | None = None, pooling_score_weight: float = 0.0, scoring: str | Callable | None = None, scoring_needs_proba: bool = False, stratify_coord: str | None = None, exclude_intertrial_from_scoring: bool = False, exclude_offsets_from_scoring: bool = False, use_stateful_fit_cache: bool = True, release_fold_memory: bool = False, verbose: bool = True)
Bases: CrossValidator
K-fold validation on target domains with sampled target-domain training trials.
Splits are created on target-domain trials only. For each fold: - validation contains one fold of target-domain trials - training contains all source-domain trials plus a sampled subset of the remaining target-domain trials
Target-domain sampling is label-conditional. Use label_sample_counts for per-label overrides and
default_samples_per_label for all other labels. A count of 0 means zero-shot for that label;
None means use all available target training samples for that label.
Source code in xdflow/cv/domain.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
score_on_holdout ¶
score_on_holdout(initial_container: DataContainer, verbose: bool = False) -> float
Fit and score on the target-domain holdout using the validator sampling policy.
Unlike the base KFoldValidator holdout path, the final training set is not
all non-holdout trials. It is all source-domain trials plus the same
label-conditional sampled subset of non-holdout target-domain trials used
during cross-validation. This keeps holdout scoring aligned with the
few-shot/zero-shot transfer regime configured for the validator.
Source code in xdflow/cv/domain.py
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | |
Leave-Group-Out Validators¶
LeaveGroupOutValidator ¶
LeaveGroupOutValidator(group_coord: str, test_group_ids: list[Hashable] | None = None, validation_group_ids: list[Hashable] | None = None, pooling_score_weight: float = 0.0, scoring: str | Callable | None = None, n_splits: int | None = None, random_state: int = 0, exclude_intertrial_from_scoring: bool = False, exclude_offsets_from_scoring: bool = False, use_stateful_fit_cache: bool = True, release_fold_memory: bool = False, scoring_needs_proba: bool = False, verbose: bool = True)
Bases: CrossValidator
Implements cross-validation by leaving one or more groups out at a time with optional holdout groups.
This validator iterates through each unique group/groups, using it as the validation set once, while all other groups are used for training. This is critical for assessing how well a model generalizes to new, unseen groups.
When n_splits is not set, one group is used for validation at a time. When n_splits is set, the groups are split into n_splits folds.
Initialize Leave-One-Group-Out cross-validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_coord
|
str
|
Coordinate to group by. |
required |
test_group_ids
|
list[Hashable] | None
|
List of group IDs to use as final holdout test set. If None or empty, no holdout set is created. |
None
|
validation_group_ids
|
list[Hashable] | None
|
List of group IDs to use as validation set. If None or empty, no validation set is created. |
None
|
pooling_score_weight
|
float
|
Interpolation factor between the average fold score (0.0) and the pooled OOF score (1.0). Defaults to 0.0. |
0.0
|
scoring
|
str | Callable | None
|
Scoring metric to use. If None, auto-selects based on task type. |
None
|
n_splits
|
int | None
|
Total number of splits to perform. If None, all groups are used. |
None
|
random_state
|
int
|
Random state for reproducibility. Used for shuffling groups if n_splits is set. |
0
|
exclude_intertrial_from_scoring
|
bool
|
Whether to drop intertrial segments during evaluation. |
False
|
use_stateful_fit_cache
|
bool
|
Whether to cache stateful transforms during CV. |
True
|
verbose
|
bool
|
Whether to print verbose output specific to cross-validation. |
True
|
Source code in xdflow/cv/leave_group_out.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | |
LeaveSessionOutValidator ¶
LeaveSessionOutValidator(test_session_ids: list[Hashable] | None = None, validation_session_ids: list[Hashable] | None = None, pooling_score_weight: float = 0.0, scoring: str | Callable | None = None, n_splits: int | None = None, random_state: int = 0, exclude_intertrial_from_scoring: bool = False, exclude_offsets_from_scoring: bool = False, use_stateful_fit_cache: bool = True, release_fold_memory: bool = False, scoring_needs_proba: bool = False, verbose: bool = True)
Bases: LeaveGroupOutValidator
Implements cross-validation by leaving one or more sessions out at a time with optional holdout sessions.
This validator iterates through each unique session/sessions, using it as the validation set once, while all other sessions are used for training. This is critical for assessing how well a model generalizes to new, unseen sessions.
Note: This is a convenience wrapper around LeaveGroupOutValidator with group_coord="session".
Initialize Leave-Session-Out cross-validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
test_session_ids
|
list[Hashable] | None
|
List of session IDs to use as final holdout test set. If None or empty, no holdout set is created. |
None
|
validation_session_ids
|
list[Hashable] | None
|
List of session IDs to use as validation set. If None or empty, no validation set is created. |
None
|
pooling_score_weight
|
float
|
Interpolation factor between the average fold score (0.0) and the pooled OOF score (1.0). Defaults to 0.0. |
0.0
|
scoring
|
str | Callable | None
|
Scoring metric to use. If None, auto-selects based on task type. |
None
|
n_splits
|
int | None
|
Total number of splits to perform. If None, all sessions are used. |
None
|
random_state
|
int
|
Random state for reproducibility. Used for shuffling sessions if n_splits is set. |
0
|
exclude_intertrial_from_scoring
|
bool
|
Whether to drop intertrial segments during evaluation. |
False
|
use_stateful_fit_cache
|
bool
|
Whether to cache stateful transforms during CV. |
True
|
verbose
|
bool
|
Whether to print verbose output specific to cross-validation. |
True
|
Source code in xdflow/cv/leave_group_out.py
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | |
LeaveAnimalOutValidator ¶
LeaveAnimalOutValidator(test_animal_ids: list[Hashable] | None = None, validation_animal_ids: list[Hashable] | None = None, pooling_score_weight: float = 0.0, scoring: str | Callable | None = None, n_splits: int | None = None, random_state: int = 0, exclude_intertrial_from_scoring: bool = False, exclude_offsets_from_scoring: bool = False, use_stateful_fit_cache: bool = True, release_fold_memory: bool = False, scoring_needs_proba: bool = False, verbose: bool = True)
Bases: LeaveGroupOutValidator
Implements cross-validation by leaving one or more animals out at a time with optional holdout animals.
This validator iterates through each unique animal/animals, using it as the validation set once, while all other animals are used for training. This is critical for assessing how well a model generalizes to new, unseen animals.
Note: This is a convenience wrapper around LeaveGroupOutValidator with group_coord="animal".
Initialize Leave-Animal-Out cross-validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
test_animal_ids
|
list[Hashable] | None
|
List of animal IDs to use as final holdout test set. If None or empty, no holdout set is created. |
None
|
validation_animal_ids
|
list[Hashable] | None
|
List of animal IDs to use as validation set. If None or empty, no validation set is created. |
None
|
pooling_score_weight
|
float
|
Interpolation factor between the average fold score (0.0) and the pooled OOF score (1.0). Defaults to 0.0. |
0.0
|
scoring
|
str | Callable | None
|
Scoring metric to use. If None, auto-selects based on task type. |
None
|
n_splits
|
int | None
|
Total number of splits to perform. If None, all animals are used. |
None
|
random_state
|
int
|
Random state for reproducibility. Used for shuffling sessions if n_splits is set. |
0
|
exclude_intertrial_from_scoring
|
bool
|
Whether to drop intertrial segments during evaluation. |
False
|
use_stateful_fit_cache
|
bool
|
Whether to cache stateful transforms during CV. |
True
|
verbose
|
bool
|
Whether to print verbose output specific to cross-validation. |
True
|
Source code in xdflow/cv/leave_group_out.py
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | |
Sklearn Adapter¶
SklearnCVAdapter ¶
SklearnCVAdapter(cross_validator)
Bases: BaseCrossValidator
Adapter that converts a CrossValidator to sklearn-compatible CV splitter.
This allows using custom CrossValidator classes (LeaveGroupOutValidator, etc.) with sklearn models that accept a cv parameter (LogisticRegressionCV, RidgeCV, etc.).
The adapter uses a context variable to receive the DataContainer during fit(), allowing it to work in nested CV scenarios where the container may change. It is intended for normal pipeline usage (including tuning) because SKLearnTransform automatically wraps estimator.fit with set_cv_container when it detects a SklearnCVAdapter. For standalone sklearn usage, the context manager must be set explicitly.
Initialize the adapter.
Parameters¶
cross_validator : CrossValidator The custom cross validator to adapt
Source code in xdflow/cv/sklearn_adapter.py
37 38 39 40 41 42 43 44 45 46 47 | |
split ¶
split(X, y=None, groups=None)
Generate indices to split data into training and test set.
Source code in xdflow/cv/sklearn_adapter.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | |
get_n_splits ¶
get_n_splits(X=None, y=None, groups=None)
Returns the number of splitting iterations in the cross-validator.
Source code in xdflow/cv/sklearn_adapter.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | |
set_cv_container ¶
set_cv_container(container: DataContainer)
Context manager to set the DataContainer for SklearnCVAdapter.
This must be used when fitting sklearn models that use SklearnCVAdapter for cross-validation, unless the estimator is wrapped in SKLearnTransform (which will set the context automatically).
Source code in xdflow/cv/sklearn_adapter.py
107 108 109 110 111 112 113 114 115 116 117 118 119 120 | |