時間序列資料的交叉驗證

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 會把資料切成多個等長的「摺疊」(fold)
  • 這是最常見的交叉驗證方式之一

      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 的 CV 行為

Python 的時間序列資料機器學習

關於隨機打散資料的說明

  • 許多 CV 疊代器可在交叉驗證時隨機打散資料。
  • 僅適用於 i.i.d. 資料,而時間序列通常並非如此。
  • 進行時間序列預測時,請勿隨機打散資料。

      from sklearn.model_selection import ShuffleSplit
    
      cv = ShuffleSplit(n_splits=3)
      for tr, tt in cv.split(X, y):
          ...
    
Python 的時間序列資料機器學習

視覺化隨機打散的 CV 行為

Python 的時間序列資料機器學習

使用時間序列的 CV 疊代器

  • 目前為止,我們在交叉驗證中打破了時間的線性順序。
  • 但一般而言,你不應該用未來的資料來預測過去。
  • 作法:一律用「過去」的訓練資料預測「未來」。
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 的時間序列資料機器學習

一起來練習吧!

Python 的時間序列資料機器學習

Preparing Video For Download...