随机森林通过使用 for 循环调整两个超参数来获得 mse

Random forest getting mse by tuning two hyperparameters using a for loop

我正在开发一个模型,使用 scikit 中的 RandomForestRegressor 来预测目标变量。

我开发了一个函数来获取 mse,如下所示:

def get_mse(n_estimators, max_leaf_nodes, X_train, X_valid, y_train, y_valid):
    model = RandomForestRegressor(n_estimators=n_estimators, max_leaf_nodes=max_leaf_nodes, random_state=0)
    model.fit(X_train, y_train)
    preds_val = model.predict(X_valid)
    mse = mean_squared_error(y_valid, preds_val, squared = False)
    return(mse)

我想使用 for 循环通过组合 n_estimators 和 max_leaf_nodes

的值列表来获得最佳 mse 分数

下面是我写的代码:

n_estimators = [100,150,200,250]
max_leaf_nodes = [10, 50, 100, 200]

for n_estimators,max_leaf_nodes in zip(n_estimators,max_leaf_nodes):
    my_mse = get_mse(n_estimators,max_leaf_nodes, X_train, X_valid, y_train, y_valid)
    print("N_estimators: %d  \t\t Max leaf nodes: %d  \t\t Mean Squared Error:  %d" %(n_estimators, max_leaf_nodes, my_mse))

但是当我 运行 这个 for 循环时,对于两个超参数的每个组合,它总是 return mse 为 0。

我已经使用以下代码尝试了我的功能,它 return 具有正确的 mse:

get_mse(200, 100, X_train, X_valid, y_train, y_valid)

我想知道为什么我的 for 循环不能正常工作,return我总是 0 mse。

有人可以帮我解决这个问题吗?

谢谢

主要考虑两点:

首先,不要隐藏您已经用于声明值列表的名称(n_estimatorsmax_leaf_nodes)。相反,让它们清晰可辨:

n_estimators_list = [100, 150, 200, 250]
max_leaf_nodes_list = [10, 50, 100, 200]

for n_estimators, max_leaf_nodes in zip(n_estimators_list, max_leaf_nodes_list):
...

其次,正如上面的评论所指出的,您应该将 mse%d 格式化程序替换为 %f,因为 0 和 1 之间的值将被格式化为 0:

print("N_estimators: %d  \t\t Max leaf nodes: %d  \t\t Mean Squared Error:  %f" %(n_estimators, max_leaf_nodes, my_mse))

就我个人而言,我建议使用一种较新的字符串格式化选项,例如 Python 3 的 f-strings,以避免此类事故:

print(f"N_estimators: {n_estimators}  \t\t Max leaf nodes: {max_leaf_nodes}  \t\t Mean Squared Error:  {my_mse}")

评论中也已经提到的最后一点:对于超参数调优,您可以使用 GridSearchCV 这是一个预先实现的功能,可以通过对预配置进行详尽搜索来找到最佳超参数定义的网格。用法示例:

param_grid = {
   'n_estimators': [100, 150, 200, 250],
   'max_leaf_nodes': [10, 50, 100, 200]
}

gs = GridSearchCV(
    estimator=RandomForestRegressor(),
    param_grid=param_grid,
    scoring='neg_root_mean_squared_error'
)

gs.fit(X, y)
print(gs.best_params_)

优点是此实现经过实战验证,提供许多现成的值和统计数据来检查结果,并使用交叉验证。此外,它将探索所有可能的超参数组合(与您自己的循环不同,后者没有)。

您可以在 documentation 中阅读有关 GridSearchCV 的更多信息。