不進行隨機重排的交叉驗證
現在,請使用區塊式交叉驗證(不對所有資料點進行隨機重排)重新執行模型擬合。在這種情況下,相鄰的時間點會彼此靠近保留。你覺得在每個交叉驗證迴圈中,模型的預測會呈現什麼樣子?
你的工作環境中已提供一個 Linear regression 的 model 物件。同時也有 X 和 y(訓練資料)陣列可用。
本練習屬於課程
Python 的時間序列資料機器學習
練習說明
- 這次請實例化另一個交叉驗證物件,使用 KFold 交叉驗證,設定為 10 個分割且不進行隨機重排。
- 迭代此物件:用訓練索引來擬合模型,並用測試索引來產生預測。
- 使用我們提供的輔助函式(
visualize_predictions())視覺化各個 CV 分割的預測結果。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create KFold cross-validation object
from sklearn.model_selection import KFold
cv = ____(n_splits=____, shuffle=____)
# Iterate through CV splits
results = []
for tr, tt in cv.split(X, y):
# Fit the model on training data
model.fit(____)
# Generate predictions on the test data and collect
prediction = model.predict(____)
results.append((prediction, tt))
# Custom function to quickly visualize predictions
visualize_predictions(results)