Validation Cross Validation#
cross_validation
#
| FUNCTION | DESCRIPTION |
|---|---|
cross_validation |
Evaluate estimator performance using cross-validation on a single dataset. |
Classes#
Functions#
cross_validation(estimator: Any, X: torch.Tensor, fit_score_fn: Callable, weights: torch.Tensor | None = None, target: torch.Tensor | None = None, n_cv: int | Any = 5, shuffle: bool = False, random_state: int | None = None, device: str | torch.device | None = None, n_jobs: int = 1, backend: str = 'threading', verbose: int = 0, pre_dispatch: str = '2*n_jobs', return_required: list[str] = ['score_test', 'score_train'], return_estimator: bool = False, return_times: bool = True, error_score: float | str = 'raise', dtype: torch.dtype = torch.float32) -> dict[str, Any]
#
Evaluate estimator performance using cross-validation on a single dataset.
Performs K-fold cross-validation by splitting data into train/test folds, fitting the estimator on each train fold, and scoring on the test fold.
This function wraps dispatch_cross_validation() with simplified interface
for single-dataset validation.
| PARAMETER | DESCRIPTION |
|---|---|
estimator
|
Unfitted estimator object. Must have
TYPE:
|
X
|
Input data of shape
TYPE:
|
fit_score_fn
|
User-defined fit and score function with signature:
TYPE:
|
weights
|
Sample weights of shape (n_samples,).
TYPE:
|
target
|
Target values of shape (n_samples,) for supervised methods.
TYPE:
|
n_cv
|
Number of cross-validation folds (int), or a CV splitter object (e.g., KFold, StratifiedKFold from sklearn).
TYPE:
|
shuffle
|
Whether to shuffle data before splitting into folds.
Only used when
TYPE:
|
random_state
|
Random seed for reproducible shuffling.
Only used when
TYPE:
|
device
|
Device to run cross-validation on ('cpu', 'cuda', 'cuda:0', etc.). If None, uses the device of input data X. When using CUDA device, parallel processing is disabled (n_jobs=1) and folds are executed sequentially on GPU.
TYPE:
|
n_jobs
|
Number of parallel jobs. -1 uses all processors. Automatically set to 1 when using CUDA device.
TYPE:
|
backend
|
Joblib backend for parallelization.
TYPE:
|
verbose
|
Verbosity level for joblib.
TYPE:
|
pre_dispatch
|
Number of jobs to pre-dispatch for parallel execution.
TYPE:
|
return_required
|
Required key to return from cross validation.
TYPE:
|
return_estimator
|
Whether to return fitted estimators from each fold.
TYPE:
|
return_times
|
Whether to include fold execution times in output.
TYPE:
|
error_score
|
Behavior on fit or score errors:
TYPE:
|
dtype
|
Data type for error score tensors.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
Dictionary with keys:
|
Examples:
Basic 5-fold cross-validation:
>>> from spectre.decomposition import PrincipalComponentAnalysis as PCA
>>> from spectre.validation import cross_validate
>>> import torch
>>>
>>> # Define fit/score callback
>>> def fit_score(est, train_data, test_data):
... train_batch = train_data["X"]
... test_batch = test_data["X"]
...
... # Fit on train fold
... est.fit(train_batch.data, weights=train_batch.weights)
...
... # Evaluate on both folds
... score_train = est.score(train_batch.data)
... score_test = est.score(test_batch.data)
...
... return {"score_train": score_train, "score_test": score_test}
>>>
>>> # Run cross-validation
>>> pca = PCA(n_components=5)
>>> X = torch.randn(100, 20)
>>> results = cross_validate(pca, X, fit_score_fn=fit_score, n_cv=5)
With shuffled K-fold and weighted samples:
>>> results = cross_validate(
... pca,
... X,
... fit_score_fn=fit_score,
... weights=torch.ones(100),
... n_cv=10,
... shuffle=True,
... random_state=42,
... )
With stratified CV splitter (for classification):
>>> from sklearn.model_selection import StratifiedKFold
>>>
>>> y = torch.randint(0, 3, (100,)) # 3 classes
>>> cv_splitter = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
>>> results = cross_validate(
... pca,
... X,
... fit_score_fn=fit_score,
... target=y,
... n_cv=cv_splitter,
... )
Parallel evaluation on CPU with fitted estimator retention:
>>> results = cross_validate(
... pca,
... X,
... fit_score_fn=fit_score,
... n_cv=5,
... n_jobs=-1, # All cores
... return_estimator=True,
... return_times=True,
... )
>>> # Access fold-specific estimators
>>> fold_1_model = results["estimator"][0]
Source code in spectre/validation/cross_validation.py
12 13 14 15 16 17 18 19 20 21 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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 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 | |