開始使用免費開始

建立時間位移的特徵

在時間序列的機器學習中,常見做法是利用前幾個時間點的資訊來預測後續的時間點。

在這個練習中,你會「位移」原始資料並將結果視覺化。你會使用上一章計算過的「百分比變化」時間序列,這次以「非常短」的視窗為例。使用短視窗很重要,因為在真實情境中,你想要的是預測時間序列的逐日波動,而不是較長期間的變化。

本練習屬於課程

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

檢視課程

練習說明

  • 使用字典生成式,依照 shifts 指定的延遲步數,建立多個 prices_perc 的時間位移版本。
  • 將結果轉換為 DataFrame。
  • 使用提供的程式碼將結果視覺化。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# These are the "time lags"
shifts = np.arange(1, 11).astype(int)

# Use a dictionary comprehension to create name: value pairs, one pair per shift
shifted_data = {"lag_{}_day".format(day_shift): prices_perc.____(____) for day_shift in shifts}

# Convert into a DataFrame for subsequent use
prices_perc_shifted = ____(shifted_data)

# Plot the first 100 samples of each
ax = prices_perc_shifted.iloc[:100].plot(cmap=plt.cm.viridis)
prices_perc.iloc[:100].plot(color='r', lw=2)
ax.legend(loc='best')
plt.show()
編輯並執行程式碼