開始使用免費開始

建立訓練與測試特徵

在擬合線性模型之前,我們要在特徵中加入常數項,這樣線性模型就會有截距。

我們也要建立訓練與測試的特徵。如此一來,我們可以用訓練資料集來擬合模型,並在測試資料集上評估效能。我們一定要在模型未見過的資料上檢查效能,以確保沒有過度擬合,也就是把訓練資料中的模式記得過於精確。

對這類時間序列,我們通常會把最舊的資料當成訓練集,最新的資料當成測試集。如此可以在最新資料上評估模型表現,更貼近尚未觀察到的新資料之預測情境。

本練習屬於課程

Python 金融 Machine Learning

檢視課程

練習說明

  • 以別名 sm 匯入 statsmodels.api 函式庫。
  • 使用 statsmodels 的 .add_constant() 函式替變數 features 加入常數項。
  • 使用 featurestargets.shape[0] 屬性,將 train_size 設為資料點總數(列數)的 85%。
  • 使用 train_size 與 Python 索引(例如 [start:stop])將 linear_featurestargets 切分為訓練集與測試集。

動手互動練習

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

# Import the statsmodels.api library with the alias sm
___

# Add a constant to the features
linear_features = sm.____(features)

# Create a size for the training set that is 85% of the total number of samples
train_size = int(0.85 * ____)
train_features = linear_features[:train_size]
train_targets = targets[____]
test_features = linear_features[train_size:]
test_targets = targets[train_size:]
print(linear_features.shape, train_features.shape, test_features.shape)
編輯並執行程式碼