---
url: /stable/api/sklink.model_selection.md
description: API reference of sklink.model_selection. Validation tools for relational data.
---

::: v-pre

# `sklink.model_selection` {#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**](#sklink.model_selection.TemporalCutoffSplit): Time-ordered cross-validation over the cutoff column of `X`.

## `sklink.model_selection.TemporalCutoffSplit` {#sklink.model_selection.TemporalCutoffSplit}

```python
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) -> None
```

Bases: [BaseCrossValidator](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.BaseCrossValidator.html)

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`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.KFold.html),
[`StratifiedKFold`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html) or
[`GroupKFold`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GroupKFold.html) 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`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TimeSeriesSplit.html), the test sets do not
cover every sample, so it cannot be used with
[`cross_val_predict`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_predict.html).

**Guides:** [Time, cutoffs and temporal cross-validation](../tutorials/time-and-cutoffs), [Model selection](../tutorials/model-selection)

**Parameters:**

* **time** ([str](https://docs.python.org/3/library/stdtypes.html#str) or [int](https://docs.python.org/3/library/functions.html#int)): Column of `X` with the cutoff of each sample: a name, or an integer
  position. It must be a position when `X` is a NumPy array. The column
  must hold dates or datetimes without missing values; timezone-aware
  values are compared in UTC.
* **n\_splits** ([int](https://docs.python.org/3/library/functions.html#int)): Number of splits. Must be at least 2.
* **gap** (([str](https://docs.python.org/3/library/stdtypes.html#str), [timedelta](https://docs.python.org/3/library/datetime.html#datetime.timedelta), [timedelta64](https://numpy.org/doc/stable/reference/generated/numpy.timedelta64.html) or None)): Extra separation between training and test cutoffs: every training
  cutoff `c` satisfies `c + label_horizon + gap <= min(test cutoffs)`.
  Strings are an integer and a unit, such as `"30D"` or `"12h"`
  (units `W`, `D`, `h`, `min`, `s`, `ms`, `us`, `ns`;
  parts can be combined, as in `"1D12h"`). `None` means no gap.
* **label_horizon** (([str](https://docs.python.org/3/library/stdtypes.html#str), [timedelta](https://docs.python.org/3/library/datetime.html#datetime.timedelta), [timedelta64](https://numpy.org/doc/stable/reference/generated/numpy.timedelta64.html) or None)): How far after its cutoff the label of a sample looks. A training
  sample is kept only if `cutoff + label_horizon + gap` does not pass
  the first test cutoff, so training labels never overlap the test
  period. Same formats as `gap`.
* **test_size** (([int](https://docs.python.org/3/library/functions.html#int), [float](https://docs.python.org/3/library/functions.html#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. `None` uses `n_distinct_cutoffs // (n_splits + 1)`
  distinct cutoffs.
* **max_train_size** ([int](https://docs.python.org/3/library/functions.html#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.
  Unlike [`TimeSeriesSplit`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TimeSeriesSplit.html), it counts
  cutoffs and not samples, so that a cutoff is never split.

sklearn.model_selection.TimeSeriesSplit : Splits by row position.

`groups` is ignored, with a warning when given, as in
[`TimeSeriesSplit`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TimeSeriesSplit.html). The splits are
deterministic and the indices of each set are sorted.

**Examples:**

```pycon
>>> 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:

```pycon
>>> 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**](#sklink.model_selection.TemporalCutoffSplit.get_n_splits): Return the number of splits.
* [**get_params**](#sklink.model_selection.TemporalCutoffSplit.get_params): Get the parameters of this splitter.
* [**set_params**](#sklink.model_selection.TemporalCutoffSplit.set_params): Set the parameters of this splitter.
* [**split**](#sklink.model_selection.TemporalCutoffSplit.split): Generate indices to split data into training and test sets.

**Attributes:**

* [**gap**](#sklink.model_selection.TemporalCutoffSplit.gap):
* [**label_horizon**](#sklink.model_selection.TemporalCutoffSplit.label_horizon):
* [**max_train_size**](#sklink.model_selection.TemporalCutoffSplit.max_train_size):
* [**n\_splits**](#sklink.model_selection.TemporalCutoffSplit.n_splits):
* [**test_size**](#sklink.model_selection.TemporalCutoffSplit.test_size):
* [**time**](#sklink.model_selection.TemporalCutoffSplit.time):

### `sklink.model_selection.TemporalCutoffSplit.gap` {#sklink.model_selection.TemporalCutoffSplit.gap}

```python
gap = gap
```

### `sklink.model_selection.TemporalCutoffSplit.get_n_splits` {#sklink.model_selection.TemporalCutoffSplit.get_n_splits}

```python
get_n_splits(X: Any = None, y: Any = None, groups: Any = None) -> int
```

Return the number of splits.

**Parameters:**

* **X** ([object](https://docs.python.org/3/library/functions.html#object)): Always ignored, exists for compatibility.
* **y** ([object](https://docs.python.org/3/library/functions.html#object)): Always ignored, exists for compatibility.
* **groups** ([object](https://docs.python.org/3/library/functions.html#object)): Always ignored, exists for compatibility.

**Returns:**

* **n\_splits** ([int](https://docs.python.org/3/library/functions.html#int)): The `n_splits` parameter.

### `sklink.model_selection.TemporalCutoffSplit.get_params` {#sklink.model_selection.TemporalCutoffSplit.get_params}

```python
get_params(deep: bool = True) -> dict[str, Any]
```

Get the parameters of this splitter.

**Parameters:**

* **deep** ([bool](https://docs.python.org/3/library/functions.html#bool)): Ignored; the splitter holds no nested estimators.

**Returns:**

* **params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Parameter names mapped to their values.

### `sklink.model_selection.TemporalCutoffSplit.label_horizon` {#sklink.model_selection.TemporalCutoffSplit.label_horizon}

```python
label_horizon = label_horizon
```

### `sklink.model_selection.TemporalCutoffSplit.max_train_size` {#sklink.model_selection.TemporalCutoffSplit.max_train_size}

```python
max_train_size = max_train_size
```

### `sklink.model_selection.TemporalCutoffSplit.n_splits` {#sklink.model_selection.TemporalCutoffSplit.n_splits}

```python
n_splits = n_splits
```

### `sklink.model_selection.TemporalCutoffSplit.set_params` {#sklink.model_selection.TemporalCutoffSplit.set_params}

```python
set_params(**params: Any) -> TemporalCutoffSplit
```

Set the parameters of this splitter.

**Parameters:**

* \*\***params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Parameter names mapped to their new values.

**Returns:**

* **self** ([TemporalCutoffSplit](#sklink.model_selection.TemporalCutoffSplit)): This splitter.

### `sklink.model_selection.TemporalCutoffSplit.split` {#sklink.model_selection.TemporalCutoffSplit.split}

```python
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 by `time`.
* **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](https://docs.python.org/3/library/exceptions.html#ValueError): If the time column is missing, not temporal or has missing values;
  if a parameter is invalid; or if the data do not allow
  `n_splits` non-empty splits.

### `sklink.model_selection.TemporalCutoffSplit.test_size` {#sklink.model_selection.TemporalCutoffSplit.test_size}

```python
test_size = test_size
```

### `sklink.model_selection.TemporalCutoffSplit.time` {#sklink.model_selection.TemporalCutoffSplit.time}

```python
time = time
```

:::
