跳转至

gridSearchCV(网格搜索)的参数、方法及示例

学习笔记

1 简介

GridSearchCV的sklearn官方网址

GridSearchCV,它存在的意义就是自动调参,只要把参数输进去,就能给出最优化的结果和参数。但是这个方法适合于小数据集,一旦数据的量级上去了,很难得出结果。这个时候就是需要动脑筋了。数据量比较大的时候可以使用一个快速调优的方法——坐标下降。它其实是一种贪心算法:拿当前对模型影响最大的参数调优,直到最优化;再拿下一个影响最大的参数调优,如此下去,直到所有的参数调整完毕。这个方法的缺点就是可能会调到局部最优而不是全局最优,但是省时间省力,巨大的优势面前,还是试一试吧,后续可以再拿bagging再优化。

通常算法不够好,需要调试参数时必不可少。比如SVM的惩罚因子C,核函数kernel,gamma参数等,对于不同的数据使用不同的参数,结果效果可能差1-5个点,sklearn为我们提供专门调试参数的函数grid_search。

2 参数说明

class sklearn.model_selection.GridSearchCV(estimator, param_grid, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch=2*n_jobs, error_score=raise, return_train_score=warn)

(1)estimator

选择使用的分类器,并且传入除需要确定最佳的参数之外的其他参数。每一个分类器都需要一个scoring参数,或者score方法:如

estimator=RandomForestClassifier(min_samples_split=100,min_samples_leaf=20,max_depth=8,max_features='sqrt',random_state=10)

(2)param_grid

需要最优化的参数的取值,值为字典或者列表,例如

param_grid = {'n_estimators':range(10,71,10)}

(3)scoring=None

模型评价标准,默认None,这时需要使用score函数;或者如scoring='roc_auc',根据所选模型不同,评价准则不同。 字符串(函数名),或是可调用对象,需要其函数签名形如:scorer(estimator, X, y); 如果是None,则使用estimator的误差估计函数。

可以通过sklearn.metrics.make_scorer(myfunc, greater_is_better=?)来自定义评分函数, 如果greater_is_better=True, 那么评分就是真实的分数, 是个>0的数; 如果greater_is_better=False, 那么评分就是真实的分数相反数, 是<0的数 自定义评分函数时的参数次序为myfunc(y_true, y_pred), 两个不要搞反了, 函数只能返回1个数

(4)fit_params=None

(5)n_jobs=1

n_jobs: 并行数,int:个数,-1:跟CPU核数一致, 1:默认值

(6)iid=True

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

(7)refit=True

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

表示搜索完后, 是否用最好的参数在给定的整个数据集上(忽略了cv参数, 包含了训练、验证集)拟合1个模型

1.如果refit=True, 可通过best_estimator_获取这个模型(注意这个模型不是只在训练集上拟合的, 而是在原先GridSearchCV.fit(X_whole,Y_whole)给定的整个数据集上(训练集+验证集)拟合的)。

2.如果refit=False, 则没有best_estimator_这个属性

(8)cv=None

交叉验证参数,默认None,使用三折交叉验证。指定fold数量,默认为3,也可以是yield训练/测试数据的生成器。

1. 使用PredefinedSplit可以指定每次fold的验证集

2. 理解PredefinedSplit可以看官方的小例子以及StackOverflow上的解答

3. 如何不用交叉验证, 而用预设的验证集?看后面的代码示例

4. 使用RepeatedKFold(n_splits=splits, n_repeats=repeats)可以做splits折交叉验证,做repeats次(比如splits=10, repeats=2, 则第一次,用1种参数跑10折得到10次结果,第二次重新划分10折,还是用一样的参数跑10折。这样相当于使用一样的参数不一样的train/val划分跑了20次 )

(9)verbose=0, scoring=None

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

(10)pre_dispatch=‘2*n_jobs’

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

(11)error_score=’raise’

(12)return_train_score=’warn’

如果“False”,cv_results_属性将不包括训练分数。

回到sklearn里面的GridSearchCV,GridSearchCV用于系统地遍历多种参数组合,通过交叉验证确定最佳效果参数。

如以下示范, 搜索完毕后可以通过best_params_来得到最优的参数. 结合原模型的预设参数 default_params = gbm.get_params(), 通过update来更新找到的最优参数: default_params.update(gsearch.best_params_) 最后重新初始化模型gbm = LGBMRegressor(**default_params),并且fit就可以了 gbm.fit(x_train, train_y)

gbm = LGBMRegressor(boosting_type='gbdt', 
                    num_leaves=20, # Maximum tree leaves for base learners.
                    max_depth=2, # Maximum tree depth for base learners, &lt;=0 means no limit.
                    learning_rate=0.1, n_estimators=30,
                    subsample_for_bin=200000, objective='regression_l1', class_weight=None,
                    min_split_gain=0., min_child_weight=1e-3, 
                    min_child_samples=20,  #Minimum number of data needed in a child (leaf).
                    subsample=1., 
                    subsample_freq=0, # 0 means disable bagging; k means perform bagging at every k iteration
                    colsample_bytree=1., # &lt;1 means LightGBM will randomly select part of features on each iteration (tree)
                    reg_alpha=0., # L1 regularization term on weights.
                    reg_lambda=0.,# L2 regularization term on weights.
                    random_state=2019,
                    n_jobs=-1, silent=True, 
                    importance_type='gain' # The type of feature importance to be filled into feature_importances_. If ‘split’, result contains numbers of times the feature is used in a model. If ‘gain’, result contains total gains of splits which use the feature.
                    )

# 网格搜索
parameters = {
        'objective': ['regression', 'regression_l1'],
        'max_depth': [2,3,4,5],
#        'num_leaves': [20,25,30,35],
#        'n_estimators': [20,25,30,35],
#        'min_child_samples': [15,20,25,30],
#        'subsample_freq': [0,2,5],
#        'subsample': [0.7,0.8,0.9,1],
#        'colsample_bytree': [0.8,0.9,1]
        }
tridx = -np.ones(x_train.shape[0])
vaidx = np.zeros(x_val.shape[0])

def mape_my(t, p):
    return np.abs((t - p)/t).mean()
scorer = make_scorer(mape_my, greater_is_better=False)

# tridx所有元素=-1表示用来训练的, vaidx所有元素=0表示用来验证的. tridx和vaidx对应下面的x_search(y_search)
# tridx值=-1表示肯定参与训练
# 参与验证的元素vaidx必须&gt;=0
# =0表示第一次cross validation的验证集, 其他不等于0的为训练集
# =1表示第二次cross validation的验证集, 其他不等于1的为训练集, 以此类推
ps = PredefinedSplit(test_fold=np.hstack([tridx, vaidx]))
gsearch = GridSearchCV(gbm, param_grid=parameters, # 前面已经用预定义了一些参数来初始化gbm, 这里只搜索'objective'和'max_depth'
                       scoring=scorer, 
                       cv=ps, verbose=10,
                       refit=False # You need to set refit=False (not a default option), otherwise the grid search will refit the estimator on the whole dataset (ignoring cv) after the grid search completes.
                       )
x_search = np.vstack([x_train, x_val])
y_search = np.concatenate([train_y, val_y],0)
gsearch.fit(x_search, y_search) # 搜索最优参数

print('参数的最佳取值:{0}'.format(gsearch.best_params_))
print('最佳模型得分:{0}'.format(gsearch.best_score_))

default_params = gbm.get_params() # 得到前面预定义的参数
default_params.update(gsearch.best_params_) # 更新最优的参数
gbm = LGBMRegressor(**default_params)
raise ValueError
"""
---------------------------------
接下来可以只用train set而不用val set拟合1个模型
gbm.fit(x_train, train_y,
        verbose=True
        )
"""

3 Scoring parameter:

评价标准参数详细说明

Model-evaluation tools using cross-validation (such as model_selection.cross_val_score andmodel_selection.GridSearchCV) rely on an internal scoring strategy. This is discussed in the section The scoring parameter: defining model evaluation rules.

For the most common use cases, you can designate a scorer object with the scoring parameter; the table below shows all possible values. All scorer objects follow the convention that higher return values are better than lower return values. Thus metrics which measure the distance between the model and the data, like metrics.mean_squared_error, are available as neg_mean_squared_error which return the negated value of the metric.

Scoring

Function

Comment

Classification

‘accuracy’

metrics.accuracy_score

‘balanced_accuracy’

metrics.balanced_accuracy_score

‘top_k_accuracy’

metrics.top_k_accuracy_score

‘average_precision’

metrics.average_precision_score

‘neg_brier_score’

metrics.brier_score_loss

‘f1’

metrics.f1_score

for binary targets

‘f1_micro’

metrics.f1_score

micro-averaged

‘f1_macro’

metrics.f1_score

macro-averaged

‘f1_weighted’

metrics.f1_score

weighted average

‘f1_samples’

metrics.f1_score

by multilabel sample

‘neg_log_loss’

metrics.log_loss

requires predict_proba support

‘precision’ etc.

metrics.precision_score

suffixes apply as with ‘f1’

‘recall’ etc.

metrics.recall_score

suffixes apply as with ‘f1’

‘jaccard’ etc.

metrics.jaccard_score

suffixes apply as with ‘f1’

‘roc_auc’

metrics.roc_auc_score

‘roc_auc_ovr’

metrics.roc_auc_score

‘roc_auc_ovo’

metrics.roc_auc_score

‘roc_auc_ovr_weighted’

metrics.roc_auc_score

‘roc_auc_ovo_weighted’

metrics.roc_auc_score

Clustering

‘adjusted_mutual_info_score’

metrics.adjusted_mutual_info_score

‘adjusted_rand_score’

metrics.adjusted_rand_score

‘completeness_score’

metrics.completeness_score

‘fowlkes_mallows_score’

metrics.fowlkes_mallows_score

‘homogeneity_score’

metrics.homogeneity_score

‘mutual_info_score’

metrics.mutual_info_score

‘normalized_mutual_info_score’

metrics.normalized_mutual_info_score

‘rand_score’

metrics.rand_score

‘v_measure_score’

metrics.v_measure_score

Regression

‘explained_variance’

metrics.explained_variance_score

‘max_error’

metrics.max_error

‘neg_mean_absolute_error’

metrics.mean_absolute_error

‘neg_mean_squared_error’

metrics.mean_squared_error

‘neg_root_mean_squared_error’

metrics.mean_squared_error

‘neg_mean_squared_log_error’

metrics.mean_squared_log_error

‘neg_median_absolute_error’

metrics.median_absolute_error

‘r2’

metrics.r2_score

‘neg_mean_poisson_deviance’

metrics.mean_poisson_deviance

‘neg_mean_gamma_deviance’

metrics.mean_gamma_deviance

‘neg_mean_absolute_percentage_error’

metrics.mean_absolute_percentage_error

4 属性

(1)cv_results_ : dict of numpy (masked) ndarrays

具有键作为列标题和值作为列的dict,可以导入到DataFrame中。注意,“params”键用于存储所有参数候选项的参数设置列表。

(2)best_estimator_ : estimator

通过搜索选择的估计器,即在左侧数据上给出最高分数(或指定的最小损失)的估计器。 如果refit = False,则不可用。

(3)best_score_ : float

best_estimator的分数

(4)best_params_ : dict

在保存数据上给出最佳结果的参数设置

(5)best_index_ : int 对应于最佳候选参数设置的索引(cv_results_数组)。

search.cv_results _ ['params'] [search.best_index_]中的dict给出了最佳模型的参数设置,给出了最高的平均分数(search.best_score_)。

(6)scorer_ : function

Scorer function used on the held out data to choose the best parameters for the model.

(7)n_splits_ : int

The number of cross-validation splits (folds/iterations).

5 进行预测的常用方法和属性

grid.fit() :运行网格搜索

grid_scores_ :给出不同参数情况下的评价结果

best_params_ :描述了已取得最佳结果的参数的组合

best_score_ :提供优化过程期间观察到的最好的评分

6 网格搜索实例

6.1 随机森林

(1)http://ju.outofmemory.cn/entry/329943 转自“ 蓝鲸网站分析博客 ”。

(2)利用sklearn api gridsearch 进行keras参数调优

1
2
3
4
5
6
param_test1 ={'n_estimators':range(10,71,10)}
gsearch1= GridSearchCV(estimator =RandomForestClassifier(min_samples_split=100,
                                 min_samples_leaf=20,max_depth=       8,max_features='sqrt',random_state=10), 
                       param_grid =param_test1,scoring='roc_auc',cv=5)
gsearch1.fit(X,y)
gsearch1.grid_scores_, gsearch1.best_params_, gsearch1.best_score_

输出结果如下:

1
2
3
4
5
6
7
8
9
([mean: 0.80681, std:0.02236, params: {'n_estimators': 10},
  mean: 0.81600, std: 0.03275, params:{'n_estimators': 20},
  mean: 0.81818, std: 0.03136, params:{'n_estimators': 30},
  mean: 0.81838, std: 0.03118, params:{'n_estimators': 40},
  mean: 0.82034, std: 0.03001, params:{'n_estimators': 50},
  mean: 0.82113, std: 0.02966, params:{'n_estimators': 60},
  mean: 0.81992, std: 0.02836, params:{'n_estimators': 70}],
{'n_estimators': 60},
0.8211334476626017)

如果有transform,使用Pipeline简化系统搭建流程,将transform与分类器串联起来(Pipelineof transforms with a final estimator)

1
2
3
4
5
6
7
8
pipeline= Pipeline([("features", combined_features), ("svm", svm)])
param_grid= dict(features__pca__n_components=[1, 2, 3],
                  features__univ_select__k=[1,2],
                  svm__C=[0.1, 1, 10])

grid_search= GridSearchCV(pipeline, param_grid=param_grid, verbose=10)
grid_search.fit(X,y)
print(grid_search.best_estimator_)

参考:

官方资料 model_evaluation

凡本网注明"来源:XXX "的文/图/视频等稿件,本网转载出于传递更多信息之目的,并不意味着赞同其观点或证实其内容的真实性。如涉及作品内容、版权和其它问题,请与本网联系,我们将在第一时间删除内容!
作者:
来源: https://www.csdn.net/tags/OtDaggysMTEyMTktYmxvZwO0O0OO0O0O.html