调优随机森林超参数
与所有模型一样,我们希望通过调优超参数来优化性能。随机森林有很多超参数,但通常最重要的是在每次分裂时抽取的特征数量,即 sklearn 库中 RandomForestRegressor 的 max_features。对于像随机森林这样内置随机性的模型,我们还需要设置 random_state,以便结果可复现。
通常我们可以使用 sklearn 的 GridSearchCV() 来搜索超参数,但在金融时间序列中,我们不希望使用交叉验证,以免数据混杂。我们希望在最早的数据上训练模型,并在最新的数据上评估。因此,我们将使用 sklearn 的 ParameterGrid 来创建要搜索的超参数组合。
本练习是课程的一部分
Python 金融机器学习
练习说明
- 在
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])