时间序列数据的交叉验证

Python 中的时间序列机器学习

Chris Holdgraf

Fellow, Berkeley Institute for Data Science

使用 scikit-learn 做交叉验证

# Iterating over the "split" method yields train/test indices
for tr, tt in cv.split(X, y):
    model.fit(X[tr], y[tr])
    model.score(X[tt], y[tt])
Python 中的时间序列机器学习

交叉验证类型:KFold

  • KFold 交叉验证将数据分成大小相等的多个"折"
  • 它是最常见的交叉验证方法之一

      from sklearn.model_selection import KFold
      cv = KFold(n_splits=5)
      for tr, tt in cv.split(X, y):
          ...
    
Python 中的时间序列机器学习

可视化模型预测

fig, axs = plt.subplots(2, 1)

# Plot the indices chosen for validation on each loop
axs[0].scatter(tt, [0] * len(tt), marker='_', s=2, lw=40)
axs[0].set(ylim=[-.1, .1], title='Test set indices (color=CV loop)', 
           xlabel='Index of raw data')

# Plot the model predictions on each iteration
axs[1].plot(model.predict(X[tt]))
axs[1].set(title='Test set predictions on each CV loop', 
           xlabel='Prediction index')
Python 中的时间序列机器学习

可视化 KFold 的交叉验证行为

Python 中的时间序列机器学习

关于打乱数据的说明

  • 许多交叉验证迭代器可在过程中打乱数据。
  • 仅当数据是 i.i.d. 时可行,而时间序列通常不是。
  • 做时间序列预测时不应打乱数据。

      from sklearn.model_selection import ShuffleSplit
    
      cv = ShuffleSplit(n_splits=3)
      for tr, tt in cv.split(X, y):
          ...
    
Python 中的时间序列机器学习

可视化打乱的交叉验证行为

Python 中的时间序列机器学习

使用时间序列交叉验证迭代器

  • 到目前为止,我们在交叉验证中打破了时间的线性顺序
  • 但通常不应用未来的数据去预测过去
  • 一种方法:始终用过去的训练数据预测未来
Python 中的时间序列机器学习

可视化时间序列交叉验证迭代器

# Import and initialize the cross-validation iterator
from sklearn.model_selection import TimeSeriesSplit
cv = TimeSeriesSplit(n_splits=10)

fig, ax = plt.subplots(figsize=(10, 5))
for ii, (tr, tt) in enumerate(cv.split(X, y)):
    # Plot training and test indices
    l1 = ax.scatter(tr, [ii] * len(tr), c=[plt.cm.coolwarm(.1)], 
                    marker='_', lw=6)
    l2 = ax.scatter(tt, [ii] * len(tt), c=[plt.cm.coolwarm(.9)], 
                    marker='_', lw=6)
    ax.set(ylim=[10, -1], title='TimeSeriesSplit behavior', 
           xlabel='data index', ylabel='CV iteration')
    ax.legend([l1, l2], ['Training', 'Validation'])
Python 中的时间序列机器学习

可视化 TimeSeriesSplit 迭代器

Python 中的时间序列机器学习

在 scikit-learn 中自定义评分函数

def myfunction(estimator, X, y):
    y_pred = estimator.predict(X)
    my_custom_score = my_custom_function(y_pred, y)
    return my_custom_score
Python 中的时间序列机器学习

为 scikit-learn 编写自定义相关系数函数

def my_pearsonr(est, X, y):
    # Generate predictions and convert to a vector 
    y_pred = est.predict(X).squeeze()

    # Use the numpy "corrcoef" function to calculate a correlation matrix
    my_corrcoef_matrix = np.corrcoef(y_pred, y.squeeze())

    # Return a single correlation value from the matrix
    my_corrcoef = my_corrcoef[1, 0]
    return my_corrcoef
Python 中的时间序列机器学习

Passons à la pratique !

Python 中的时间序列机器学习

Preparing Video For Download...