我正试图解决一个机器学习问题。我有一个带有时间序列元素的特定数据集。对于这个问题,我使用了著名的python库sklearn
。这个库中有很多交叉验证迭代器。还有一些迭代器可以自己定义交叉验证。问题是,我真的不知道如何定义时间序列的简单交叉验证。这里有一个很好的例子,我正在努力得到:
假设我们有几个周期(年),我们想将数据集划分为几个块,如下所示:
data = [1, 2, 3, 4, 5, 6, 7]
train: [1] test: [2] (or test: [2, 3, 4, 5, 6, 7])
train: [1, 2] test: [3] (or test: [3, 4, 5, 6, 7])
train: [1, 2, 3] test: [4] (or test: [4, 5, 6, 7])
...
train: [1, 2, 3, 4, 5, 6] test: [7]
我真的不明白如何用sklearn工具创建这种交叉验证。也许我应该像这样使用sklearn.cross_validation
中的PredefinedSplit
:
train_fraction = 0.8
train_size = int(train_fraction * X_train.shape[0])
validation_size = X_train.shape[0] - train_size
cv_split = cross_validation.PredefinedSplit(test_fold=[-1] * train_size + [1] * validation_size)
结果:
train: [1, 2, 3, 4, 5] test: [6, 7]
但它仍然不如以前的数据分割
您可以在不使用sklearn
的情况下获得所需的交叉验证拆分。这里有一个的例子
import numpy as np
from sklearn.svm import SVR
from sklearn.feature_selection import RFECV
# Generate some data.
N = 10
X_train = np.random.randn(N, 3)
y_train = np.random.randn(N)
# Define the splits.
idxs = np.arange(N)
cv_splits = [(idxs[:i], idxs[i:]) for i in range(1, N)]
# Create the RFE object and compute a cross-validated score.
svr = SVR(kernel="linear")
rfecv = RFECV(estimator=svr, step=1, cv=cv_splits)
rfecv.fit(X_train, y_train)
同时将其添加到库中:http://scikit-learn.org/stable/modules/cross_validation.html#time-串联拆分
文档示例:
>>> 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(n_splits=3)
>>> print(tscv)
TimeSeriesSplit(n_splits=3)
>>> for train, test in tscv.split(X):
... print("%s %s" % (train, test))
[0 1 2] [3]
[0 1 2 3] [4]
[0 1 2 3 4] [5]