机器学习之网格搜索(GridSearch)及参数说明,实例演示

一)GridSearchCV简介
网格搜索(GridSearch)用于选取模型的最优超参数。获取最优超参数的方式可以绘制验证曲线,但是验证曲线只能每次获取一个最优超参数。如果多个超参数有很多排列组合的话,就可以使用网格搜索寻求最优超参数的组合。

网格搜索针对超参数组合列表中的每一个组合,实例化给定的模型,做cv次交叉验证,将平均得分最高的超参数组合作为最佳的选择,返回模型对象。
GridSearchCV的sklearn官方网址:
http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV

二)sklearn.model_selection.GridSearchCV参数详解

sklearn.model_selection.GridSearchCV(
estimator, 
param_grid, 
scoring=None,
 n_jobs=None,
 iid=’warn’, 
refit=True, 
cv=’warn’, 
verbose=0, 
pre_dispatch=‘2*n_jobs’, 
error_score=’raise-deprecating’, 
return_train_score=False)

(1) estimator

选择使用的分类器,并且传入除需要确定最佳的参数之外的其他参数。
(2) param_grid

需要最优化的参数的取值,值为字典或者列表。
(3) scoring=None

模型评价标准,默认None。
根据所选模型不同,评价准则不同。比如scoring=”accuracy”。
如果是None,则使用estimator的误差估计函数。
https://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter (官方文档)
Scoring的参数,如下图:

ScoringFunctionComment
Classification
‘accuracy’metrics.accuracy_score
‘average_precision’ metrics.average_precision_score
‘f1’metrics.f1_scorefor binary targets
‘f1_micro’metrics.f1_scoremicro-averaged
‘f1_macro’metrics.f1_scoremacro-averaged
‘f1_weighted’metrics.f1_scoreweighted average
‘f1_samples’metrics.f1_scoreby multilabel sample
‘neg_log_loss’metrics.log_lossrequires predict_proba support
‘precision’ etc.metrics.precision_scoresuffixes apply as with ‘f1’
‘roc_auc’metrics.roc_auc_score
‘recall’ etc.metrics.recall_scoresuffixes apply as with ‘f1’
Clustering
‘adjusted_rand_score’metrics.adjusted_rand_score
Regression
‘neg_mean_absolute_error’metrics.mean_absolute_error
‘neg_mean_squared_error’metrics.mean_squared_error
‘neg_median_absolute_error’metrics.median_absolute_error
‘r2’metrics.r2_score
(4) n_jobs=1 进程个数,默认为1。 若值为 -1,则用所有的CPU进行运算。 若值为1,则不进行并行运算,这样的话方便调试。 (5) iid=True

默认True,为True时,默认为各个样本fold概率分布一致,误差估计为所有样本之和,而非各个fold的平均。

(6) refit=True

默认为True,程序将会以交叉验证训练集得到的最佳参数,重新对所有可用的训练集与开发集进行,作为最终用于性能评估的最佳模型参数。即在搜索参数结束后,用最佳参数结果再次fit一遍全部数据集。

(7) cv=None

交叉验证参数,默认None,使用三折交叉验证。

(8) verbose=0,
verbose:日志冗长度
0:不输出训练过程,
1:偶尔输出,>1:对每个子模型都输出。

(9) pre_dispatch=‘2*n_jobs’

指定总共分发的并行任务数。当n_jobs大于1时,数据将在每个运行点进行复制,这可能导致OOM,而设置pre_dispatch参数,则可以预先划分总共的job数量,使数据最多被复制pre_dispatch次

三)以鸢尾花数据集为例,基于网格搜索得到最优模型

import numpy as np
import sklearn.model_selection as ms
import sklearn.svm as svm #导入svm函数
from sklearn.datasets import load_iris  #导入鸢尾花数据
iris = load_iris()
x = iris.data
y = iris.target
# 可以看到样本大概分为三类
print(x[:5])
print(y)

out:

[[5.1 3.5 1.4 0.2]
 [4.9 3.  1.4 0.2]
 [4.7 3.2 1.3 0.2]
 [4.6 3.1 1.5 0.2]
 [5.  3.6 1.4 0.2]]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2]
# 基于svm 实现分类
model = svm.SVC(probability=True)
# 基于网格搜索获取最优模型
params = [
	{'kernel':['linear'],'C':[1,10,100,1000]},
	{'kernel':['poly'],'C':[1,10],'degree':[2,3]},
	{'kernel':['rbf'],'C':[1,10,100,1000], 
	 'gamma':[1,0.1, 0.01, 0.001]}]
model = ms.GridSearchCV(estimator=model, param_grid=params, cv=5)	 
model.fit(x, y)
# 网格搜索训练后的副产品
print("模型的最优参数:",model.best_params_)
print("最优模型分数:",model.best_score_)
print("最优模型对象:",model.best_estimator_)

out:

模型的最优参数: {'C': 1, 'kernel': 'linear'}
最优模型分数: 0.98
最优模型对象: SVC(C=1, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape='ovr', degree=3, gamma='auto_deprecated',
  kernel='linear', max_iter=-1, probability=True, random_state=None,
  shrinking=True, tol=0.001, verbose=False)
# 输出网格搜索每组超参数的cv数据
for p, s in zip(model.cv_results_['params'],
	model.cv_results_['mean_test_score']):
	print(p, s)

out:

{'C': 1, 'kernel': 'linear'} 0.98
{'C': 10, 'kernel': 'linear'} 0.9733333333333334
{'C': 100, 'kernel': 'linear'} 0.9666666666666667
{'C': 1000, 'kernel': 'linear'} 0.9666666666666667
{'C': 1, 'degree': 2, 'kernel': 'poly'} 0.9733333333333334
{'C': 1, 'degree': 3, 'kernel': 'poly'} 0.9666666666666667
{'C': 10, 'degree': 2, 'kernel': 'poly'} 0.9666666666666667
{'C': 10, 'degree': 3, 'kernel': 'poly'} 0.9666666666666667
{'C': 1, 'gamma': 1, 'kernel': 'rbf'} 0.9666666666666667
{'C': 1, 'gamma': 0.1, 'kernel': 'rbf'} 0.98
{'C': 1, 'gamma': 0.01, 'kernel': 'rbf'} 0.9333333333333333
{'C': 1, 'gamma': 0.001, 'kernel': 'rbf'} 0.9133333333333333
{'C': 10, 'gamma': 1, 'kernel': 'rbf'} 0.9533333333333334
{'C': 10, 'gamma': 0.1, 'kernel': 'rbf'} 0.98
{'C': 10, 'gamma': 0.01, 'kernel': 'rbf'} 0.98
{'C': 10, 'gamma': 0.001, 'kernel': 'rbf'} 0.9333333333333333
{'C': 100, 'gamma': 1, 'kernel': 'rbf'} 0.94
{'C': 100, 'gamma': 0.1, 'kernel': 'rbf'} 0.9666666666666667
{'C': 100, 'gamma': 0.01, 'kernel': 'rbf'} 0.98
{'C': 100, 'gamma': 0.001, 'kernel': 'rbf'} 0.98
{'C': 1000, 'gamma': 1, 'kernel': 'rbf'} 0.9333333333333333
{'C': 1000, 'gamma': 0.1, 'kernel': 'rbf'} 0.9533333333333334
{'C': 1000, 'gamma': 0.01, 'kernel': 'rbf'} 0.9666666666666667
{'C': 1000, 'gamma': 0.001, 'kernel': 'rbf'} 0.98

四)疑问
我在看其他博客的时候,别人有提到说:“网格搜索这个方法适合于小数据集,一旦数据的量级上去了,就很难得出结果。这个时候可以使用一个快速调优的方法——坐标下降。拿当前对模型影响最大的参数调优,直到最优化;再拿下一个影响最大的参数调优,如此下去,直到所有的参数调整完毕。这个方法的缺点就是可能会调到局部最优而不是全局最优,但是省时间省力。” 我不太明白这个小数据集,它的体量是什么范围,如果你知道,不妨留言告诉我,谢谢。

  • 37
    点赞
  • 232
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
好的,下面是一个 Gradient Boosting Regressor 机器学习模型超参数调整的实例: 假设我们有一个数据集,其中包含了一些房屋的信息,包括房屋的面积、卧室数量、浴室数量、车库数量、位置等等。我们的目标是预测每个房屋的售价。 我们可以使用 Gradient Boosting Regressor 来建立一个预测模型。在建立模型之前,我们需要确定一些超参数,例如 learning_rate、n_estimators、max_depth、min_samples_split 等等。这些超参数可以影响模型的性能和训练时间。 下面是一个简单的超参数调整实例: 1. 导入必要的库和数据集 ```python import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_squared_error data = pd.read_csv('housing.csv') ``` 2. 数据预处理 ```python # 删除缺失值 data.dropna(inplace=True) # 将类别变量转换为数值变量 data = pd.get_dummies(data) # 将数据集分为特征和目标变量 X = data.drop('SalePrice', axis=1) y = data['SalePrice'] # 将数据集分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ``` 3. 定义超参数范围 ```python # 定义超参数范围 param_grid = { 'learning_rate': [0.01, 0.1, 1], 'n_estimators': [100, 500, 1000], 'max_depth': [3, 5, 7], 'min_samples_split': [2, 4, 8] } ``` 4. 使用网格搜索确定最佳超参数 ```python from sklearn.model_selection import GridSearchCV # 定义模型 model = GradientBoostingRegressor() # 定义网格搜索 grid_search = GridSearchCV(estimator=model, param_grid=param_grid, cv=5, n_jobs=-1) # 运行网格搜索 grid_search.fit(X_train, y_train) # 输出最佳超参数 print(grid_search.best_params_) # 输出最佳模型 best_model = grid_search.best_estimator_ ``` 5. 训练模型并进行预测 ```python # 训练模型 best_model.fit(X_train, y_train) # 预测测试集 y_pred = best_model.predict(X_test) # 计算均方误差 mse = mean_squared_error(y_test, y_pred) print('均方误差:', mse) ``` 通过上面的步骤,我们可以使用网格搜索确定最佳超参数,并训练一个性能良好的 Gradient Boosting Regressor 模型。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值