開始使用免費開始

調整隨機森林的超參數

和所有模型一樣,我們會透過調整超參數來最佳化效能。隨機森林有許多超參數,但最重要的通常是每次分割時要抽樣的特徵數,也就是 sklearn 函式庫中 RandomForestRegressormax_features。對於像隨機森林這種內含隨機性的模型,我們也要設定 random_state,以便讓結果可重現。

一般情況下,我們可以用 sklearn 的 GridSearchCV() 來搜尋超參數。不過在金融時間序列中,為了避免資料混雜,我們不做交叉驗證。我們會用較舊的資料來訓練模型,並用最新的資料來評估。因此,我們將使用 sklearn 的 ParameterGrid 來建立要搜尋的超參數組合。

本練習屬於課程

Python 金融 Machine Learning

檢視課程

練習說明

  • grid 字典中,將 n_estimators 超參數設為只包含一個數值(200)的清單。
  • grid 字典中,將 max_features 超參數設為包含 4 與 8 的清單。
  • 在迴圈中,對於每一組超參數組合 g,將隨機森林迴歸模型(rfr,已為你建立)配適到 train_featurestrain_targets
  • 使用 rfr.score() 作用於 test_features 計算 R$^2$,並將結果加入 test_scores 清單。

動手互動練習

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

from sklearn.model_selection import ParameterGrid

# Create a dictionary of hyperparameters to search
grid = {____, 'max_depth': [3], 'max_features': ____, 'random_state': [42]}
test_scores = []

# Loop through the parameter grid, set the hyperparameters, and save the scores
for g in ParameterGrid(grid):
    rfr.set_params(**g)  # ** is "unpacking" the dictionary
    rfr.fit(____, ____)
    test_scores.append(rfr.score(____, ____))

# Find best hyperparameters from the test score and print
best_idx = np.argmax(test_scores)
print(test_scores[best_idx], ParameterGrid(grid)[best_idx])
編輯並執行程式碼