scikit-learn交叉验证时间序列数据的自定义拆分

Ben*_*Ben 10 python machine-learning scikit-learn

我想使用scikit-learn的GridSearchCV来确定随机森林模型的一些超参数.我的数据是时间依赖的,看起来像

import pandas as pd

train = pd.DataFrame({'date': pd.DatetimeIndex(['2012-1-1', '2012-9-30', '2013-4-3', '2014-8-16', '2015-3-20', '2015-6-30']), 
'feature1': [1.2, 3.3, 2.7, 4.0, 8.2, 6.5],
'feature2': [4, 4, 10, 3, 10, 9],
'target': [1,2,1,3,2,2]})

>>> train
        date  feature1  feature2  target
0 2012-01-01       1.2         4       1
1 2012-09-30       3.3         4       2
2 2013-04-03       2.7        10       1
3 2014-08-16       4.0         3       3
4 2015-03-20       8.2        10       2
5 2015-06-30       6.5         9       2
Run Code Online (Sandbox Code Playgroud)

如何实现以下交叉验证折叠技术?

train:(2012, 2013) - test:(2014)
train:(2013, 2014) - test:(2015)
Run Code Online (Sandbox Code Playgroud)

也就是说,我想用2年的历史观察来训练模型,然后在接下来的一年里测试它的准确性.

ely*_*ase 12

您只需将带有拆分的iterable传递给GridSearchCV.此拆分应具有以下格式:

[
 (split1_train_idxs, split1_test_idxs),
 (split2_train_idxs, split2_test_idxs),
 (split3_train_idxs, split3_test_idxs),
 ...
]
Run Code Online (Sandbox Code Playgroud)

要获得idx,您可以执行以下操作:

groups = df.groupby(df.date.dt.year).groups
# {2012: [0, 1], 2013: [2], 2014: [3], 2015: [4, 5]}
sorted_groups = [value for (key, value) in sorted(groups.items())] 
# [[0, 1], [2], [3], [4, 5]]

cv = [(sorted_groups[i] + sorted_groups[i+1], sorted_groups[i+2])
      for i in range(len(sorted_groups)-2)]
Run Code Online (Sandbox Code Playgroud)

这看起来像这样:

[([0, 1, 2], [3]),  # idxs of first split as (train, test) tuple
 ([2, 3], [4, 5])]  # idxs of second split as (train, test) tuple
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

GridSearchCV(estimator, param_grid, cv=cv, ...)
Run Code Online (Sandbox Code Playgroud)


vil*_*asv 6

有一个标准的sklearn方法,使用GroupShuffleSplit. 从文档:

提供随机训练/测试索引以根据第三方提供的组拆分数据。该组信息可用于将样本的任意领域特定分层编码为整数。

例如,组可以是样本收集的年份,因此允许针对基于时间的拆分进行交叉验证。

非常方便您的用例。这是它的样子:

cv = GroupShuffleSplit().split(X, y, groups)
Run Code Online (Sandbox Code Playgroud)

并将其传递给GridSearchCV之前喜欢:

GridSearchCV(estimator, param_grid, cv=cv, ...)
Run Code Online (Sandbox Code Playgroud)


mlo*_*ing 5

中的TimeSeriesSplit函数还可以sklearn在火车/测试集中拆分时间序列数据(即具有固定的时间间隔)。请注意,与标准的交叉验证方法不同,连续的训练集是它们之前的训练集的超集,即,在每个拆分中,测试索引必须比以前更高,因此在交叉验证器中改组是不合适的。