
在使用scikit-learn库进行机器学习模型训练时,尤其是在进行超参数调优(Hyperparameter Tuning)时,我们经常需要尝试不同的超参数组合。一种常见的做法是将这些超参数组合存储在一个字典列表中,然后通过循环迭代这些字典,为每次迭代构建一个模型实例。
然而,对于像RandomForestRegressor这样的scikit-learn估计器,其构造函数期望的是一系列独立的关键字参数,而不是一个单一的字典对象。当尝试将一个包含所有超参数的字典直接作为第一个位置参数传递给构造函数时,例如 RandomForestRegressor(hparams),scikit-learn会将其误认为是要设置的某个特定参数(通常是第一个参数,如n_estimators),并尝试将整个字典赋值给它。由于字典类型与预期参数类型(例如n_estimators期望整数)不匹配,便会抛出InvalidParameterError。
错误示例代码:
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_regression
# 模拟数据
X, y = make_regression(n_samples=100, n_features=5, random_state=42)
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
},
{
'n_estimators':60,
'bootstrap':False,
'criterion':'friedman_mse',
'max_depth':90,
'max_features':3,
'min_samples_leaf':1,
'min_samples_split':2
}]
for hparams_dict in hyperparams:
try:
# 错误示范:直接传递字典
model_regressor = RandomForestRegressor(hparams_dict)
print(f"尝试参数集: {hparams_dict}")
model_regressor.fit(X_train, y_train)
print("模型训练成功!")
except Exception as e:
print(f"在参数集 {hparams_dict} 下发生错误: {e}")
# 错误信息将类似于:
# 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', ...} instead.上述代码将产生一个InvalidParameterError,明确指出n_estimators参数收到了一个字典,而不是预期的整数。这正是因为RandomForestRegressor的构造函数签名不接受一个完整的字典作为其参数。
Python提供了一个强大的字典解包(Dictionary Unpacking)运算符 **。当在一个函数调用中使用时,**运算符会将字典中的键值对解包为独立的关键字参数。
例如,如果有一个字典 {'a': 1, 'b': 2},使用 ** 解包后,它就等同于 a=1, b=2。这正是scikit-learn估计器构造函数所期望的格式。
正确使用字典解包的示例代码:
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_regression
from sklearn.metrics import r2_score, mean_squared_error
# 模拟数据
X, y = make_regression(n_samples=100, n_features=5, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义超参数列表
hyperparams_list = [{
'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
}]
results = []
for i, hparams_dict in enumerate(hyperparams_list):
print(f"\n--- 正在使用第 {i+1} 组超参数: {hparams_dict} ---")
# 正确做法:使用 ** 解包字典为关键字参数
model_regressor = RandomForestRegressor(**hparams_dict)
# 打印模型参数以验证是否正确设置
print("模型实例化后的参数:", model_regressor.get_params())
# 模型训练
model_regressor.fit(X_train, y_train)
print("模型训练成功!")
# 模型评估
y_pred = model_regressor.predict(X_test)
r2 = r2_score(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
print(f"R^2 Score: {r2:.4f}")
print(f"Mean Squared Error: {mse:.4f}")
results.append({
'hyperparameters': hparams_dict,
'r2_score': r2,
'mean_squared_error': mse
})
print("\n--- 所有超参数组合的评估结果 ---")
for res in results:
print(f"超参数: {res['hyperparameters']}, R^2: {res['r2_score']:.4f}, MSE: {res['mean_squared_error']:.4f}")
通过在 RandomForestRegressor(hparams_dict) 前面加上 **,Python解释器会将 hparams_dict 字典中的每个键视为一个参数名,将其对应的值视为该参数的值,然后以 参数名=值 的形式传递给 RandomForestRegressor 的构造函数。例如,{'n_estimators': 460, 'max_depth': 60} 就会被解包成 n_estimators=460, max_depth=60。
参数名称匹配: 确保字典中的键名与RandomForestRegressor构造函数接受的参数名完全一致(包括大小写)。如果存在不匹配的键,scikit-learn会抛出TypeError,提示收到了一个意外的关键字参数。
参数类型: 字典中对应的值必须是scikit-learn期望的参数类型。例如,n_estimators必须是整数,bootstrap必须是布尔值。
超参数调优工具: 虽然手动循环超参数字典在某些简单场景下可行,但在更复杂的超参数调优任务中,强烈推荐使用scikit-learn提供的专用工具,如GridSearchCV和RandomizedSearchCV。这些工具不仅能自动化超参数组合的生成和模型训练,还集成了交叉验证、结果统计和最佳参数选择等功能,极大地简化了调优流程。
使用 GridSearchCV 的示例:
from sklearn.model_selection import GridSearchCV
# 定义超参数网格
param_grid = {
'n_estimators': [50, 100, 200],
'max_depth': [None, 10, 20],
'min_samples_leaf': [1, 2],
'criterion': ['squared_error', 'absolute_error'] # 'poisson'在较新版本中可能不支持,这里使用常用值
}
# 创建RandomForestRegressor实例
rfr = RandomForestRegressor(random_state=42)
# 创建GridSearchCV对象
grid_search = GridSearchCV(estimator=rfr, param_grid=param_grid,
cv=3, n_jobs=-1, verbose=2, scoring='r2')
# 执行网格搜索
grid_search.fit(X_train, y_train)
print("\n--- GridSearchCV 结果 ---")
print(f"最佳超参数: {grid_search.best_params_}")
print(f"最佳R^2分数: {grid_search.best_score_:.4f}")
# 使用最佳模型进行预测
best_model = grid_search.best_estimator_
y_pred_best = best_model.predict(X_test)
print(f"最佳模型在测试集上的R^2: {r2_score(y_test, y_pred_best):.4f}")GridSearchCV和RandomizedSearchCV内部会自动处理超参数的传递,无需手动解包。
在Python中,当需要通过循环迭代不同的超参数组合来实例化RandomForestRegressor(或其他scikit-learn估计器)时,务必使用字典解包运算符**将超参数字典转换为独立的关键字参数。例如,将model = RandomForestRegressor(hparams_dict)修改为model = RandomForestRegressor(**hparams_dict)。这不仅能避免InvalidParameterError,还能确保模型能够正确地接收和应用所需的超参数。对于更复杂的超参数调优场景,推荐使用scikit-learn内置的GridSearchCV或RandomizedSearchCV工具。
以上就是如何在循环中向RandomForestRegressor传递超参数字典的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号