不平衡面板数据:如何使用时间序列拆分交叉验证?

Unbalanced Panel data: How to use Time Series Splits Cross-Validation?

我目前正在处理一个大的不平衡数据集,想知道是否可以使用 sklearn 的时间序列分割交叉验证将我的训练样本分割成几个 'folds'。我希望每个折叠仅包含该特定折叠时间范围内的横截面观察。

如前所述,我正在处理一个不平衡的面板数据集,它利用了 Pandas 的多索引。这里有一个可重现的例子来提供更多的直觉:

arrays = [np.array(['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'D', 'D']),
           np.array(['2000-01', '2000-02', '2000-03', '1999-12', '2000-01', 
          '2000-01', '2000-02', '1999-12', '2000-01', '2000-02', '2000-03'])]

s = pd.DataFrame(np.random.randn(11, 4), index=arrays)

然后看起来如下:

例如,我希望最初将 1999-12 年的所有横截面单位作为训练样本,并将 2000-01 年的所有横截面单位作为验证样本。接下来,我希望将 1999-12 和 2000-01 中的所有横截面单元作为训练,并将 2000-02 中的所有横截面单元作为验证,等等。使用 TimeSeriesSplit 函数是否可行,或者我需要查看其他地方吗?

TimeSeriesSplitKFold 的变体,可确保在每个连续折叠中递增索引值。如文档中所述:

In each split, test indices must be higher than before... [also] note that unlike standard cross-validation methods, successive training sets are supersets of those that come before them.

docs

还要记住 KFoldTimeSeriesSplit return 指数 。您已经有了所需的索引。

一个问题是访问 MultiIndex 中的 DateTimeIndex 切片过于困难和复杂。参见 , here and here。由于此时您正在提取数据,因此重置索引和切片似乎是可以接受的。特别是因为重置索引不会发生。

最后,我建议将 datetime-like 索引转换为实际的日期时间数据类型。

import pandas as pd
import numpy as np
import datetime
arrays = [np.array(['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'D', 'D']),
           np.array(['2000-01', '2000-02', '2000-03', '1999-12', '2000-01', 
          '2000-01', '2000-02', '1999-12', '2000-01', '2000-02', '2000-03'])]

# Cast as datetime
arrays[1] = pd.to_datetime(arrays[1])


df = pd.DataFrame(np.random.randn(11, 4), index=arrays)
df.index.sort_values()


folds = df.reset_index() # df still has its multindex after this

# You can tack an .iloc[:, 2:] to the end of these lines for just the values
# Use your predefined conditions to access the datetimes
fold1 = folds[folds["level_1"] <=datetime.datetime(2000, 1, 1)]
fold2 = folds[folds["level_1"] == datetime.datetime(2000, 2, 1)]
fold3 = folds[folds["level_1"] == datetime.datetime(2000, 3, 1)]