使用scikit-learn的交叉验证对时间序列数据进行自定义分割

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

import pandas as pdtrain = 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  target0 2012-01-01       1.2         4       11 2012-09-30       3.3         4       22 2013-04-03       2.7        10       13 2014-08-16       4.0         3       34 2015-03-20       8.2        10       25 2015-06-30       6.5         9       2

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

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

也就是说,我想使用两年的历史观测数据来训练模型,然后在随后的年份测试其准确性。


回答:

你只需要将包含分割的可迭代对象传递给GridSearchCV。这个分割应该具有以下格式:

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

要获取这些索引,你可以这样做:

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]),  # 第一分割的索引作为(训练,测试)元组 ([2, 3], [4, 5])]  # 第二分割的索引作为(训练,测试)元组

然后你可以这样做:

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

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注