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

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

本文介绍了scikit-learn交叉验证针对时间序列数据的自定义拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用scikit-learn的 GridSearchCV

I'd like to use scikit-learn's GridSearchCV to determine some hyper parameters for a random forest model. My data is time dependent and looks something like

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

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

How can I implement the following cross validation folding technique?

train:(2012, 2013) - test:(2014)
train:(2013, 2014) - test:(2015)

也就是说,我想使用2年的历史观测数据来训练模型,然后在接下来的一年中测试其准确性.

That is, I want to use 2 years of historic observations to train a model and then test its accuracy in the subsequent year.

推荐答案

您只需要将带有拆分的可迭代对象传递给GridSearchCV.此拆分应采用以下格式:

You just have to pass an iterable with the splits to GridSearchCV. This split should have the following format:

[
 (split1_train_idxs, split1_test_idxs),
 (split2_train_idxs, split2_test_idxs),
 (split3_train_idxs, split3_test_idxs),
 ...
]

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

To get the idxs you can do something like this:

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)]

这看起来像这样:

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

那么你可以做:

GridSearchCV(estimator, param_grid, cv=cv, ...)

这篇关于scikit-learn交叉验证针对时间序列数据的自定义拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!