3.2. Grid Search: Searching for estimator parameters
3.2. Grid Search: Searching for estimator parameters
Parameters that are not directly learnt within estimators can be set by searching a parameter space for the best Cross-validation: evaluating estimator performance score. Typical examples include C, kernel and gamma for Support Vector Classifier, alpha for Lasso, etc.
Any parameter provided when constructing an estimator may be optimized in this manner. Specifically, to find the names and current values for all parameters for a given estimator, use:
estimator.get_params()
Such parameters are often referred to as hyperparameters (particularly in Bayesian learning), distinguishing them from the parameters optimised in a machine learning procedure.
A search consists of:
- an estimator (regressor or classifier such as sklearn.svm.SVC());
- a parameter space;
- a method for searching or sampling candidates;
- a cross-validation scheme; and
- a score function.
Some models allow for specialized, efficient parameter search strategies, outlined below. Two generic approaches to sampling search candidates are provided in scikit-learn: for given values, GridSearchCV exhaustively considers all parameter combinations, while RandomizedSearchCV can sample a given number of candidates from a parameter space with a specified distribution. After describing these tools we detail best practice applicable to both approaches.
3.2.1. Exhaustive Grid Search
The grid search provided by GridSearchCV exhaustively generates candidates from a grid of parameter values specified with the param_grid parameter. For instance, the following param_grid:
param_grid = [
{'C': [1, 10, 100, 1000], 'kernel': ['linear']},
{'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001], 'kernel': ['rbf']},
]
specifies that two grids should be explored: one with a linear kernel and C values in [1, 10, 100, 1000], and the second one with an RBF kernel, and the cross-product of C values ranging in [1, 10, 100, 1000] and gamma values in [0.001, 0.0001].
The GridSearchCV instance implements the usual estimator API: when “fitting” it on a dataset all the possible combinations of parameter values are evaluated and the best combination is retained.
Examples:
- See Parameter estimation using grid search with cross-validation for an example of Grid Search computation on the digits dataset.
- See Sample pipeline for text feature extraction and evaluation for an example of Grid Search coupling parameters from a text documents feature extractor (n-gram count vectorizer and TF-IDF transformer) with a classifier (here a linear SVM trained with SGD with either elastic net or L2 penalty) using a pipeline.Pipeline instance.
3.2.2. Randomized Parameter Optimization
While using a grid of parameter settings is currently the most widely used method for parameter optimization, other search methods have more favourable properties. RandomizedSearchCV implements a randomized search over parameters, where each setting is sampled from a distribution over possible parameter values. This has two main benefits over an exhaustive search:
- A budget can be chosen independent of the number of parameters and possible values.
- Adding parameters that do not influence the performance does not decrease efficiency.
Specifying how parameters should be sampled is done using a dictionary, very similar to specifying parameters forGridSearchCV. Additionally, a computation budget, being the number of sampled candidates or sampling iterations, is specified using the n_iter parameter. For each parameter, either a distribution over possible values or a list of discrete choices (which will be sampled uniformly) can be specified:
[{'C': scipy.stats.expon(scale=100), 'gamma': scipy.stats.expon(scale=.1),
'kernel': ['rbf'], 'class_weight':['auto', None]}]
This example uses the scipy.stats module, which contains many useful distributions for sampling parameters, such as expon,gamma, uniform or randint. In principle, any function can be passed that provides a rvs (random variate sample) method to sample a value. A call to the rvs function should provide independent random samples from possible parameter values on consecutive calls.
Warning
The distributions in scipy.stats do not allow specifying a random state. Instead, they use the global numpy random state, that can be seeded via np.random.seed or set using np.random.set_state.
For continuous parameters, such as C above, it is important to specify a continuous distribution to take full advantage of the randomization. This way, increasing n_iter will always lead to a finer search.
Examples:
- Comparing randomized search and grid search for hyperparameter estimation compares the usage and efficiency of randomized search and grid search.
References:
- Bergstra, J. and Bengio, Y., Random search for hyper-parameter optimization, The Journal of Machine Learning Research (2012)
3.2.3. Tips for parameter search
3.2.3.1. Specifying an objective metric
By default, parameter search uses the score function of the estimator to evaluate a parameter setting. These are thesklearn.metrics.accuracy_score for classification and sklearn.metrics.r2_score for regression. For some applications, other scoring functions are better suited (for example in unbalanced classification, the accuracy score is often uninformative). An alternative scoring function can be specified via the scoring parameter to GridSearchCV,RandomizedSearchCV and many of the specialized cross-validation tools described below. See The scoring parameter: defining model evaluation rules for more details.
3.2.3.2. Composite estimators and parameter spaces
Pipeline: chaining estimators describes building composite estimators whose parameter space can be searched with these tools.
3.2.3.3. Model selection: development and evaluation
Model selection by evaluating various parameter settings can be seen as a way to use the labeled data to “train” the parameters of the grid.
When evaluating the resulting model it is important to do it on held-out samples that were not seen during the grid search process: it is recommended to split the data into a development set (to be fed to the GridSearchCV instance) and anevaluation set to compute performance metrics.
This can be done by using the cross_validation.train_test_split utility function.
3.2.3.4. Parallelism
GridSearchCV and RandomizedSearchCV evaluate each parameter setting independently. Computations can be run in parallel if your OS supports it, by using the keyword n_jobs=-1. See function signature for more details.
3.2.3.5. Robustness to failure
Some parameter settings may result in a failure to fit one or more folds of the data. By default, this will cause the entire search to fail, even if some parameter settings could be fully evaluated. Setting error_score=0 (or =np.NaN) will make the procedure robust to such failure, issuing a warning and setting the score for that fold to 0 (or NaN), but completing the search.
3.2.4. Alternatives to brute force parameter search
3.2.4.1. Model specific cross-validation
Some models can fit data for a range of value of some parameter almost as efficiently as fitting the estimator for a single value of the parameter. This feature can be leveraged to perform a more efficient cross-validation used for model selection of this parameter.
The most common parameter amenable to this strategy is the parameter encoding the strength of the regularizer. In this case we say that we compute the regularization path of the estimator.
Here is the list of such models:
| linear_model.ElasticNetCV([l1_ratio, eps, ...]) | Elastic Net model with iterative fitting along a regularization path |
| linear_model.LarsCV([fit_intercept, ...]) | Cross-validated Least Angle Regression model |
| linear_model.LassoCV([eps, n_alphas, ...]) | Lasso linear model with iterative fitting along a regularization path |
| linear_model.LassoLarsCV([fit_intercept, ...]) | Cross-validated Lasso, using the LARS algorithm |
| linear_model.LogisticRegressionCV([Cs, ...]) | Logistic Regression CV (aka logit, MaxEnt) classifier. |
| linear_model.MultiTaskElasticNetCV([...]) | Multi-task L1/L2 ElasticNet with built-in cross-validation. |
| linear_model.MultiTaskLassoCV([eps, ...]) | Multi-task L1/L2 Lasso with built-in cross-validation. |
| linear_model.OrthogonalMatchingPursuitCV([...]) | Cross-validated Orthogonal Matching Pursuit model (OMP) |
| linear_model.RidgeCV([alphas, ...]) | Ridge regression with built-in cross-validation. |
| linear_model.RidgeClassifierCV([alphas, ...]) | Ridge classifier with built-in cross-validation. |
3.2.4.2. Information Criterion
Some models can offer an information-theoretic closed-form formula of the optimal estimate of the regularization parameter by computing a single regularization path (instead of several when using cross-validation).
Here is the list of models benefitting from the Aikike Information Criterion (AIC) or the Bayesian Information Criterion (BIC) for automated model selection:
| linear_model.LassoLarsIC([criterion, ...]) | Lasso model fit with Lars using BIC or AIC for model selection |
3.2.4.3. Out of Bag Estimates
When using ensemble methods base upon bagging, i.e. generating new training sets using sampling with replacement, part of the training set remains unused. For each classifier in the ensemble, a different part of the training set is left out.
This left out portion can be used to estimate the generalization error without having to rely on a separate validation set. This estimate comes “for free” as no additional data is needed and can be used for model selection.
This is currently implemented in the following classes:
| ensemble.RandomForestClassifier([...]) | A random forest classifier. |
| ensemble.RandomForestRegressor([...]) | A random forest regressor. |
| ensemble.ExtraTreesClassifier([...]) | An extra-trees classifier. |
| ensemble.ExtraTreesRegressor([n_estimators, ...]) | An extra-trees regressor. |
| ensemble.GradientBoostingClassifier([loss, ...]) | Gradient Boosting for classification. |
| ensemble.GradientBoostingRegressor([loss, ...]) | Gradient Boosting for regression. |
3.2. Grid Search: Searching for estimator parameters的更多相关文章
- scikit-learn:3.2. Grid Search: Searching for estimator parameters
參考:http://scikit-learn.org/stable/modules/grid_search.html GridSearchCV通过(蛮力)搜索參数空间(參数的全部可能组合).寻找最好的 ...
- How to Grid Search Hyperparameters for Deep Learning Models in Python With Keras
Hyperparameter optimization is a big part of deep learning. The reason is that neural networks are n ...
- Grid Search学习
转自:https://www.cnblogs.com/ysugyl/p/8711205.html Grid Search:一种调参手段:穷举搜索:在所有候选的参数选择中,通过循环遍历,尝试每一种可能性 ...
- Comparing randomized search and grid search for hyperparameter estimation
Comparing randomized search and grid search for hyperparameter estimation Compare randomized search ...
- Grid search in the tidyverse
@drsimonj here to share a tidyverse method of grid search for optimizing a model's hyperparameters. ...
- Extjs4.2 Grid搜索Ext.ux.grid.feature.Searching的使用
背景 Extjs4.2 默认提供的Search搜索,功能还是非常强大的,只是对于国内的用户来说,还是不习惯在每列里面单击好几下再筛选,于是相当当初2.2里面的搜索,更加的实用点,于是在4.2里面实现. ...
- grid search 超参数寻优
http://scikit-learn.org/stable/modules/grid_search.html 1. 超参数寻优方法 gridsearchCV 和 RandomizedSearchC ...
- Ext.ux.grid.feature.Searching 解析查询参数,动态产生linq lambda表达式
上篇文章中http://www.cnblogs.com/qidian10/p/3209439.html我们介绍了如何使用Grid的查询组建,而且将查询的参数传递到了后台. 那么我们后台如何介绍参数,并 ...
- [转载]Grid Search
[转载]Grid Search 初学机器学习,之前的模型都是手动调参的,效果一般.同学和我说他用了一个叫grid search的方法.可以实现自动调参,顿时感觉非常高级.吃饭的时候想调参的话最差不过也 ...
随机推荐
- ArrayList and LinkedList
ArrayList and LinkedList List代表一种线性表的数据结构,ArrayList则是一种顺序存储的线性表.ArrayList底层采用数组来保存每个集合元素,LinkedList则 ...
- python google play
#!/usr/env python #-*- coding: utf-8 -*- import urllib import urllib2 import random import requests ...
- Win7无法设置背景图片的快速解决办法
不知道怎么回事,win7电脑突然连个性化设置背景图片的按钮都没了.真操蛋~~~满屏的黑色背景图案,看着实在是不爽. 为了解决这个问题,网上搜索了好长时间,都不尽然! 最后想到了一个超简单的方法就是: ...
- XtraReport交叉表隐藏列标题及自定义排序
1.隐藏列标题 用DevExpress PivotGrid report 做报表的时候,将字段拖放到报表中后,ColumnArea和DataArea会显示两个标题字段,如下图: 选中交叉表,设置以下属 ...
- TOJ 2732存钱计划(三)(单源最短路)
存钱计划(三) 时间限制(普通/Java):1000MS/30000MS 运行内存限制:65536KByte 总提交: 18 测试通过: 16 描述 TZC的店铺比较 ...
- C程序中唯一序列号的生成
在实际的软件开发项目中.常常会涉及唯一序列号的生成.本文以一个实际的程序为例,介绍了唯一序列号的生成过程. 本文生成的序列号的样式为:MMDDHHMINSS_XXXXXX. 程序例如以下: /**** ...
- Java基础知识强化之集合框架笔记34:List练习之集合的嵌套遍历
1. 需求: 我们班有学生,每一个学生是不是一个对象.所以我们可以使用一个集合表示我们班级的学生.ArrayList<Student> 但是呢,我们旁边是不是还有班级,每个班级是不是也是一 ...
- Web通信中的Get、Post方法
首先我们要了解Tomcat,Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP 程序的首选. ...
- js中浮点型运算 注意点
先看张图: 这是一个JS浮点数运算Bug,导致我树状图,数据合计不正确,,,,,,两个小数相加,出来那么多位小数 (这是修该之后的) 网上找到以下解决方式: 方法一:有js自定义函数 <sc ...
- Android学习笔记(广播机制)
1.Android的广播机制介绍 收听收音机也是一种广播,在收音机中有很多个广播电台,每个广播电台播放的内容都不相同.接受广播时广播(发送方)并不在意我们(接收方)接收到广播时如何处理.好比我们收听交 ...