開始使用免費開始

隨機抽樣的交叉驗證

如你所知,交叉驗證會把資料多次分割為訓練集與測試集。每次都會選擇「不同的」訓練集與測試集。在這個練習中,你將對先前的公司價值資料執行傳統的 ShuffleSplit 交叉驗證。之後我們會說明針對時間序列資料需要做哪些調整。這裡使用的仍是多家大型公司的歷史股價資料。

你的工作空間中已提供一個線性迴歸物件(model),以及用於評分的 r2_score() 函式。資料則儲存在陣列 Xy 中。我們也提供了一個輔助函式(visualize_predictions())來協助你視覺化結果。

本練習屬於課程

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

檢視課程

練習說明

  • 初始化一個具有 10 次分割的 ShuffleSplit 交叉驗證物件。
  • 使用此物件迭代各個 CV 分割。每次迭代請:
    • 使用訓練索引擬合模型。
    • 使用測試索引產生預測,利用預測來計算模型分數($R^2$),並收集結果。

動手互動練習

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

# Import ShuffleSplit and create the cross-validation object
from sklearn.model_selection import ShuffleSplit
cv = ____(____, random_state=1)

# Iterate through CV splits
results = []
for tr, tt in cv.____(X, y):
    # Fit the model on training data
    ____(X[tr], y[tr])
    
    # Generate predictions on the test data, score the predictions, and collect
    prediction = ____(X[tt])
    score = r2_score(____, ____)
    results.append((prediction, score, tt))

# Custom function to quickly visualize predictions
visualize_predictions(results)
編輯並執行程式碼