調整隨機森林的超參數
和所有模型一樣,我們會透過調整超參數來最佳化效能。隨機森林有許多超參數,但最重要的通常是每次分割時要抽樣的特徵數,也就是 sklearn 函式庫中 RandomForestRegressor 的 max_features。對於像隨機森林這種內含隨機性的模型,我們也要設定 random_state,以便讓結果可重現。
一般情況下,我們可以用 sklearn 的 GridSearchCV() 來搜尋超參數。不過在金融時間序列中,為了避免資料混雜,我們不做交叉驗證。我們會用較舊的資料來訓練模型,並用最新的資料來評估。因此,我們將使用 sklearn 的 ParameterGrid 來建立要搜尋的超參數組合。
本練習屬於課程
Python 金融 Machine Learning
練習說明
- 在
grid字典中,將n_estimators超參數設為只包含一個數值(200)的清單。 - 在
grid字典中,將max_features超參數設為包含 4 與 8 的清單。 - 在迴圈中,對於每一組超參數組合
g,將隨機森林迴歸模型(rfr,已為你建立)配適到train_features與train_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])