sklearn超参数调整方法 [GridSearchCV, RandomizedSearchCV]

模型调整, 假设已经找到了一些潜在的模型,下面是几种方法用于模型调整

1. 超参数修改

  • 网格搜索 (grid searh)
    一种方法是手动调整超参数(hyperparameters)。
    GridSearchCV,参数为你想调整的超参数和该超参数的值。
    class sklearn.model_selection.GridSearchCV(estimator, param_grid, scoring=None, fit_params=None, n_jobs=None, iid=’warn’, refit=True, cv=’warn’, verbose=0, pre_dispatch=‘2*n_jobs’, error_score=’raise-deprecating’, return_train_score=’warn’)
    参数:
  • estimator sklearn实现的estimator接口,需要提供score函数,或者有scoring参数
  • param_id: 字典或字典的列表
    [{需要调整的超参数1: 超参数的可能的值}, { {需要调整的超参数2: 超参数的可能的值}}, ], 注意一个字典内为一组超参数的组合方式
  • scoring: 误差函数
  • cv : 将训练集分为多少个folds

属性:

  • best_params

  • cv_results_

from sklearn.model_selection import GridSearchCV
param_grid = [
{
    'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8]},
{
    'bootstrap': [False], 'n_estimators': [3, 10], 'max_features': [2, 3, 4]},
]

forest_reg = RandomForestRegressor()
grid_search = GridSearchCV(forest_reg, param_grid, cv=5,
                          scoring='neg_mean_squared_error')

grid_search.fit(housing_prepared, housing_labels)


sklearn 根据param_grid的值,首先会评估 3 × 4 = 12 3 \times 4 = 12 3×4=12种n_estimators和max_features的组合方式,接下来在会在bootstrap=False的情况下(默认该值为True),评估 2 × 3 = 6 2 \times3 =6 2×3=6种12种n_estimators和max_features的组合方式,所以最终会有 12 + 6 = 18 12+6=18 12+6=18种不同的超参数组合方式,
而每一种组合方式要在训练集上训练5次, 所以一共要训练 18 × 5 = 90 18 \times 5 = 90 18×5=90次,当训练结束后,你可以通过best_params_获得最好的组合方式

grid_search.best_params_

out:

{‘max_features’: 8, ‘n_estimators’: 30}

得到最好的模型

grid_search.best_estimator_

out:

RandomForestRegressor(bootstrap=True, criterion=‘mse’, max_depth=None,
max_features=8, max_leaf_nodes=None, min_impurity_decrease=0.0,
min_impurity_split=None, min_samples_leaf=1,
min_samples_split=2, min_weight_fraction_leaf=0.0,
n_estimators=30, n_jobs=1, oob_score=False, random_state=None,
verbose=0, warm_start=False)

如果GridSearchCV初始化时,refit=True(默认的初始化值),在交叉验证时,一旦发现最好的模型(estimator),将会在整个训练集上重新训练,这通常是一个好主意,因为使用更多的数据集会提升模型的性能。

cv_results_:将结果存在一个字典里, 可以转化为DataFrame类型,每一行为一种超参数组合方式。

cv = pd.DataFrame(grid_search.cv_results_
cv

# out:



	mean_fit_time	std_fit_time	mean_score_time	std_score_time	param_max_features	param_n_estimators	param_bootstrap	params	split0_test_score	split1_test_score	...	mean_test_score	std_test_score	rank_test_score	split0_train_score	split1_train_score	split2_train_score	split3_train_score	split4_train_score	mean_train_score	std_trai
  • 5
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值