sklink.model_selection
Validation tools for relational data.
In the static case, the default, use the scikit-learn splitters unchanged (KFold, StratifiedKFold, GroupKFold). TemporalCutoffSplit is for models in temporal mode.
Classes:
- TemporalCutoffSplit: Time-ordered cross-validation over the cutoff column of
X.
sklink.model_selection.TemporalCutoffSplit
TemporalCutoffSplit(time: str | int, *, n_splits: int = 5, gap: Duration | None = None, label_horizon: Duration | None = None, test_size: int | float | None = None, max_train_size: int | None = None) -> NoneBases: BaseCrossValidator
Time-ordered cross-validation over the cutoff column of X.
Splits are defined by cutoff values, not by row positions: X does not have to be sorted, and all samples with the same cutoff fall on the same side of a split. In every split, each training cutoff is earlier than every test cutoff. Training windows grow with each split (an expanding window) unless max_train_size is set.
Use it with a model in temporal mode (built with time=). For static data, use the scikit-learn splitters unchanged: KFold, StratifiedKFold or GroupKFold with groups=X[key].
The same entity can appear in training and in test with different cutoffs; that is expected in temporal prediction. As with TimeSeriesSplit, the test sets do not cover every sample, so it cannot be used with cross_val_predict.
Guides: Time, cutoffs and temporal cross-validation, Model selection
Parameters:
- time (
str or int): Column ofXwith the cutoff of each sample: a name, or an integer position. It must be a position whenXis a NumPy array. The column must hold dates or datetimes without missing values; timezone-aware values are compared in UTC. - n_splits (
int): Number of splits. Must be at least 2. - gap (
(str, timedelta, timedelta64 or None)): Extra separation between training and test cutoffs: every training cutoffcsatisfiesc + label_horizon + gap <= min(test cutoffs). Strings are an integer and a unit, such as"30D"or"12h"(unitsW,D,h,min,s,ms,us,ns; parts can be combined, as in"1D12h").Nonemeans no gap. - label_horizon (
(str, timedelta, timedelta64 or None)): How far after its cutoff the label of a sample looks. A training sample is kept only ifcutoff + label_horizon + gapdoes not pass the first test cutoff, so training labels never overlap the test period. Same formats asgap. - test_size (
(int, float or None)): Size of each test block. An integer is a number of distinct cutoffs; a float in (0, 1) is the approximate fraction of samples, rounded to whole cutoffs.Noneusesn_distinct_cutoffs // (n_splits + 1)distinct cutoffs. - max_train_size (
int or None): Maximum number of distinct cutoffs in a training set: the most recent ones are kept, which turns the expanding window into a sliding one. UnlikeTimeSeriesSplit, it counts cutoffs and not samples, so that a cutoff is never split.
See Also
sklearn.model_selection.TimeSeriesSplit : Splits by row position.
Notes
groups is ignored, with a warning when given, as in TimeSeriesSplit. The splits are deterministic and the indices of each set are sorted.
Examples:
>>> import numpy as np
>>> from sklink.model_selection import TemporalCutoffSplit
>>> cutoffs = np.array(
... ["2024-01-01", "2024-02-01", "2024-03-01", "2024-04-01"],
... dtype="datetime64[D]",
... )
>>> X = np.empty((8, 2), dtype=object)
>>> X[:, 0] = [1, 2, 1, 2, 1, 2, 1, 2]
>>> X[:, 1] = np.repeat(cutoffs, 2)
>>> cv = TemporalCutoffSplit(time=1, n_splits=3)
>>> for train, test in cv.split(X):
... print(train, test)
[0 1] [2 3]
[0 1 2 3] [4 5]
[0 1 2 3 4 5] [6 7]A label that looks 40 days ahead excludes the training cutoffs whose label period reaches the test period:
>>> cv = TemporalCutoffSplit(time=1, n_splits=2, label_horizon="40D")
>>> for train, test in cv.split(X):
... print(train, test)
[0 1] [4 5]
[0 1 2 3] [6 7]Functions:
- get_n_splits: Return the number of splits.
- get_params: Get the parameters of this splitter.
- set_params: Set the parameters of this splitter.
- split: Generate indices to split data into training and test sets.
Attributes:
sklink.model_selection.TemporalCutoffSplit.gap
gap = gapsklink.model_selection.TemporalCutoffSplit.get_n_splits
get_n_splits(X: Any = None, y: Any = None, groups: Any = None) -> intReturn the number of splits.
Parameters:
- X (
object): Always ignored, exists for compatibility. - y (
object): Always ignored, exists for compatibility. - groups (
object): Always ignored, exists for compatibility.
Returns:
- n_splits (
int): Then_splitsparameter.
sklink.model_selection.TemporalCutoffSplit.get_params
get_params(deep: bool = True) -> dict[str, Any]Get the parameters of this splitter.
Parameters:
- deep (
bool): Ignored; the splitter holds no nested estimators.
Returns:
- params (
dict): Parameter names mapped to their values.
sklink.model_selection.TemporalCutoffSplit.label_horizon
label_horizon = label_horizonsklink.model_selection.TemporalCutoffSplit.max_train_size
max_train_size = max_train_sizesklink.model_selection.TemporalCutoffSplit.n_splits
n_splits = n_splitssklink.model_selection.TemporalCutoffSplit.set_params
set_params(**params: Any) -> TemporalCutoffSplitSet the parameters of this splitter.
Parameters:
- **params (
dict): Parameter names mapped to their new values.
Returns:
- self (
TemporalCutoffSplit): This splitter.
sklink.model_selection.TemporalCutoffSplit.split
split(X: Any, y: Any = None, groups: Any = None) -> Iterator[tuple[NDArray[np.intp], NDArray[np.intp]]]Generate indices to split data into training and test sets.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_features)): Population table with the cutoff column named bytime. - y (
array-like of shape (n_samples,)): Target; only its length is checked. - groups (
array-like of shape (n_samples,)): Always ignored, exists for compatibility.
Yields:
- train (
ndarray): The training set indices for that split, sorted. - test (
ndarray): The testing set indices for that split, sorted.
Raises:
ValueError: If the time column is missing, not temporal or has missing values; if a parameter is invalid; or if the data do not allown_splitsnon-empty splits.
sklink.model_selection.TemporalCutoffSplit.test_size
test_size = test_sizesklink.model_selection.TemporalCutoffSplit.time
time = time