当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python sklearn TimeSeriesSplit用法及代码示例


本文简要介绍python语言中 sklearn.model_selection.TimeSeriesSplit 的用法。

用法:

class sklearn.model_selection.TimeSeriesSplit(n_splits=5, *, max_train_size=None, test_size=None, gap=0)

时间序列cross-validator

提供训练/测试索引以拆分在训练/测试集中以固定时间间隔观察到的时间序列数据样本。在每次拆分中,测试指标必须高于以前,因此交叉验证器中的洗牌是不合适的。

此交叉验证对象是 KFold 的变体。在第 k 次拆分中,它返回前 k 折作为训练集,第 (k+1) 折作为测试集。

请注意,与标准交叉验证方法不同,连续训练集是之前的训练集的超集。

在用户指南中阅读更多信息。

参数

n_splits整数,默认=5

分割数。必须至少为 2。

max_train_size整数,默认=无

单个训练集的最大大小。

test_size整数,默认=无

用于限制测试集的大小。默认为 n_samples // (n_splits + 1) ,这是 gap=0 允许的最大值。

gap整数,默认=0

在测试集之前从每个训练集末尾排除的样本数。

注意

训练集在第 i 次拆分中的大小为 i * n_samples // (n_splits + 1) + n_samples % (n_splits + 1),默认情况下测试集的大小为 n_samples//(n_splits + 1),其中 n_samples 是样本数。

例子

>>> 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 train_index, test_index in tscv.split(X):
...     print("TRAIN:", train_index, "TEST:", test_index)
...     X_train, X_test = X[train_index], X[test_index]
...     y_train, y_test = y[train_index], y[test_index]
TRAIN: [0] TEST: [1]
TRAIN: [0 1] TEST: [2]
TRAIN: [0 1 2] TEST: [3]
TRAIN: [0 1 2 3] TEST: [4]
TRAIN: [0 1 2 3 4] TEST: [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 train_index, test_index in tscv.split(X):
...    print("TRAIN:", train_index, "TEST:", test_index)
...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]
TRAIN: [0 1 2 3 4 5] TEST: [6 7]
TRAIN: [0 1 2 3 4 5 6 7] TEST: [8 9]
TRAIN: [0 1 2 3 4 5 6 7 8 9] TEST: [10 11]
>>> # Add in a 2 period gap
>>> tscv = TimeSeriesSplit(n_splits=3, test_size=2, gap=2)
>>> for train_index, test_index in tscv.split(X):
...    print("TRAIN:", train_index, "TEST:", test_index)
...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]
TRAIN: [0 1 2 3] TEST: [6 7]
TRAIN: [0 1 2 3 4 5] TEST: [8 9]
TRAIN: [0 1 2 3 4 5 6 7] TEST: [10 11]

相关用法


注:本文由纯净天空筛选整理自scikit-learn.org大神的英文原创作品 sklearn.model_selection.TimeSeriesSplit。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。