TimeSeriesSplit#
- class sklearn.model_selection.TimeSeriesSplit(n_splits=5, *, max_train_size=None, test_size=None, gap=0)[源代码]#
时间序列交叉验证器。
提供训练/测试索引以分割按时间排序的数据,因为其他交叉验证方法不适用,它们会导致在未来数据上训练并在过去数据上评估。为确保各折叠之间的指标具有可比性,样本必须等距。一旦满足此条件,每个测试集覆盖相同的时间长度,而训练集大小则累积来自先前分割的数据。
此交叉验证对象是
KFold
的变体。在第 k 次分割中,它将前 k 折作为训练集,将第 (k+1) 折作为测试集。请注意,与标准交叉验证方法不同,后续训练集是其前一个训练集的超集。
更多信息请参阅用户指南。
有关交叉验证行为的可视化以及常见 scikit-learn 分割方法之间的比较,请参阅可视化 scikit-learn 中的交叉验证行为
在 0.18 版本中添加。
- 参数:
- n_splitsint, 默认值=5
分割次数。必须至少为 2。
在 0.22 版本中更改:
n_splits
的默认值从 3 更改为 5。- max_train_sizeint, 默认值=None
单个训练集的最大大小。
- test_sizeint, 默认值=None
用于限制测试集的大小。默认为
n_samples // (n_splits + 1)
,这是当gap=0
时允许的最大值。在 0.24 版本中添加。
- gapint, 默认值=0
在测试集之前,从每个训练集末尾排除的样本数量。
在 0.24 版本中添加。
备注
在第
i
次分割中,训练集的大小为i * n_samples // (n_splits + 1) + n_samples % (n_splits + 1)
,测试集的大小默认为n_samples//(n_splits + 1)
,其中n_samples
是样本数量。请注意,此公式仅在test_size
和max_train_size
使用默认值时才有效。示例
>>> import numpy as np >>> from sklearn.model_selection import TimeSeriesSplit >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]]) >>> y = np.array([1, 2, 3, 4, 5, 6]) >>> tscv = TimeSeriesSplit() >>> print(tscv) TimeSeriesSplit(gap=0, max_train_size=None, n_splits=5, test_size=None) >>> for i, (train_index, test_index) in enumerate(tscv.split(X)): ... print(f"Fold {i}:") ... print(f" Train: index={train_index}") ... print(f" Test: index={test_index}") Fold 0: Train: index=[0] Test: index=[1] Fold 1: Train: index=[0 1] Test: index=[2] Fold 2: Train: index=[0 1 2] Test: index=[3] Fold 3: Train: index=[0 1 2 3] Test: index=[4] Fold 4: Train: index=[0 1 2 3 4] Test: index=[5] >>> # Fix test_size to 2 with 12 samples >>> X = np.random.randn(12, 2) >>> y = np.random.randint(0, 2, 12) >>> tscv = TimeSeriesSplit(n_splits=3, test_size=2) >>> for i, (train_index, test_index) in enumerate(tscv.split(X)): ... print(f"Fold {i}:") ... print(f" Train: index={train_index}") ... print(f" Test: index={test_index}") Fold 0: Train: index=[0 1 2 3 4 5] Test: index=[6 7] Fold 1: Train: index=[0 1 2 3 4 5 6 7] Test: index=[8 9] Fold 2: Train: index=[0 1 2 3 4 5 6 7 8 9] Test: index=[10 11] >>> # Add in a 2 period gap >>> tscv = TimeSeriesSplit(n_splits=3, test_size=2, gap=2) >>> for i, (train_index, test_index) in enumerate(tscv.split(X)): ... print(f"Fold {i}:") ... print(f" Train: index={train_index}") ... print(f" Test: index={test_index}") Fold 0: Train: index=[0 1 2 3] Test: index=[6 7] Fold 1: Train: index=[0 1 2 3 4 5] Test: index=[8 9] Fold 2: Train: index=[0 1 2 3 4 5 6 7] Test: index=[10 11]
有关更详细的示例,请参阅时间相关特征工程。
- get_metadata_routing()[源代码]#
获取此对象的元数据路由。
请查看用户指南,了解路由机制的工作原理。
- 返回:
- routingMetadataRequest
一个包含路由信息的
MetadataRequest
对象。