
在使用scikit-learn进行机器学习模型训练时,我们经常需要尝试不同的超参数组合来优化模型性能。一种常见的方法是定义一个包含多组超参数的列表,然后通过循环迭代每组超参数来实例化和训练模型。然而,当尝试将一个完整的超参数字典直接传递给RandomForestRegressor的构造函数时,通常会遇到sklearn.utils._param_validation.InvalidParameterError。
例如,考虑以下超参数字典列表:
hyperparams = [{
'n_estimators': 460,
'bootstrap': False,
'criterion': 'poisson',
'max_depth': 60,
'max_features': 2,
'min_samples_leaf': 1,
'min_samples_split': 2
},
{
'n_estimators': 60,
'bootstrap': False,
'criterion': 'friedman_mse',
'max_depth': 90,
'max_features': 3,
'min_samples_leaf': 1,
'min_samples_split': 2
}]
for hparams in hyperparams:
# 错误示例:直接传递字典
# model_regressor = RandomForestRegressor(hparams)
# ... 后续代码当执行model_regressor = RandomForestRegressor(hparams)时,scikit-learn会抛出如下错误:
sklearn.utils._param_validation.InvalidParameterError: The 'n_estimators' parameter of RandomForestRegressor must be an int in the range [1, inf). Got {'n_estimators': 460, 'bootstrap': False, 'criterion': 'poisson', 'max_depth': 60, 'max_features': 2, 'min_samples_leaf': 1, 'min_samples_split': 2} instead.这个错误信息清晰地指出,RandomForestRegressor的n_estimators参数期望一个整数,但它实际接收到的却是一个完整的字典。这是因为RandomForestRegressor的构造函数在没有明确指定关键字参数的情况下,会将第一个位置参数解释为n_estimators。因此,当我们直接传入hparams字典时,模型试图将整个字典赋值给n_estimators,从而导致类型不匹配的错误。
Python的字典解包运算符**(double-asterisk)是解决此问题的关键。它允许我们将一个字典的键值对作为关键字参数传递给函数。当在一个函数调用中使用**后跟一个字典时,字典中的每个键都会被视为一个参数名,其对应的值则作为该参数的值。
将上述错误代码修正为:
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score, mean_squared_error
# 假设有X_train, y_train数据
# 为了示例完整性,创建一些虚拟数据
X = np.random.rand(100, 5)
y = np.random.rand(100) * 100
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
hyperparams = [{
'n_estimators': 460,
'bootstrap': False,
'criterion': 'poisson',
'max_depth': 60,
'max_features': 2,
'min_samples_leaf': 1,
'min_samples_split': 2,
'random_state': 42 # 添加random_state以确保结果可复现
},
{
'n_estimators': 60,
'bootstrap': False,
'criterion': 'friedman_mse',
'max_depth': 90,
'max_features': 3,
'min_samples_leaf': 1,
'min_samples_split': 2,
'random_state': 42
}]
print("开始模型训练和评估...")
for i, hparams in enumerate(hyperparams):
print(f"\n--- 正在使用第 {i+1} 组超参数进行训练 ---")
print(f"超参数: {hparams}")
# 正确做法:使用字典解包运算符 **
model_regressor = RandomForestRegressor(**hparams)
# 验证模型参数是否正确设置
print("模型初始化参数:", model_regressor.get_params())
total_r2_score_value = 0
total_mean_squared_error_value = 0 # 修正变量名
total_tests = 5 # 减少循环次数以便快速运行示例
for index in range(1, total_tests + 1):
print(f" - 训练轮次 {index}/{total_tests}")
# 模型拟合
model_regressor.fit(X_train, y_train)
# 进行预测
y_pred = model_regressor.predict(X_test)
# 计算评估指标
r2 = r2_score(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
total_r2_score_value += r2
total_mean_squared_error_value += mse
print(f" R2 Score: {r2:.4f}, Mean Squared Error: {mse:.4f}")
# 计算平均评估指标
avg_r2 = total_r2_score_value / total_tests
avg_mse = total_mean_squared_error_value / total_tests
print(f"\n第 {i+1} 组超参数平均结果:")
print(f" 平均 R2 Score: {avg_r2:.4f}")
print(f" 平均 Mean Squared Error: {avg_mse:.4f}")
print("\n所有超参数组合评估完成。")在这个修正后的代码中,RandomForestRegressor(**hparams)这行代码将hparams字典中的'n_estimators': 460、'bootstrap': False等键值对,分别作为n_estimators=460、bootstrap=False等关键字参数传递给了RandomForestRegressor的构造函数。这样,模型就能正确地识别并设置每一个超参数,从而避免了InvalidParameterError。
参数名称匹配: 确保字典中的键名与RandomForestRegressor构造函数接受的参数名完全一致。任何拼写错误都将导致TypeError,提示函数接收到意外的关键字参数。
默认参数: 如果字典中没有包含某个参数,该参数将使用RandomForestRegressor的默认值。
替代方案:GridSearchCV 或 RandomizedSearchCV: 对于更复杂的超参数调优任务,手动循环迭代超参数组合可能效率低下且难以管理。scikit-learn提供了GridSearchCV和RandomizedSearchCV等工具,它们专门用于系统地探索超参数空间,并能自动处理交叉验证和模型选择。这些工具是进行超参数优化的推荐方法。
from sklearn.model_selection import GridSearchCV
# 定义参数网格
param_grid = {
'n_estimators': [50, 100, 200],
'max_depth': [10, 20, 30, None],
'min_samples_split': [2, 5, 10]
}
# 实例化RandomForestRegressor
rfr = RandomForestRegressor(random_state=42)
# 实例化GridSearchCV
grid_search = GridSearchCV(estimator=rfr, param_grid=param_grid,
cv=3, n_jobs=-1, verbose=2, scoring='neg_mean_squared_error')
# 执行网格搜索
grid_search.fit(X_train, y_train)
print("\n--- GridSearchCV 结果 ---")
print("最佳参数:", grid_search.best_params_)
print("最佳得分 (负均方误差):", grid_search.best_score_)
print("最佳模型:", grid_search.best_estimator_)可读性与维护性: 尽管字典解包非常方便,但在定义超参数字典时,保持清晰的结构和命名规范有助于代码的可读性和未来的维护。
在Python的scikit-learn中,当需要以字典形式传递超参数给RandomForestRegressor或其他模型构造函数时,务必使用字典解包运算符**。这能确保字典中的键值对被正确地解析为关键字参数,从而避免因类型不匹配而导致的InvalidParameterError。虽然手动循环结合字典解包适用于简单的超参数探索,但对于更全面的调优,推荐使用GridSearchCV或RandomizedSearchCV等内置工具。
以上就是如何在循环中将字典形式的超参数传递给RandomForestRegressor的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号