一. GridSearchCV参数介绍

导入模块:

from sklearn.model_selection import GridSearchCV
GridSearchCV 称为网格搜索交叉验证调参,它通过遍历传入的参数的所有排列组合,通过交叉验证的方式,返回所有参数组合下的评价指标得分,GridSearchCV 函数的参数详细解释如下:
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=True)

GridSearchCV官方说明

参数:

  • estimator:scikit-learn 库里的算法模型;
  • param_grid:需要搜索调参的参数字典;
  • scoring:评价指标,可以是 auc, rmse,logloss等;
  • n_jobs:并行计算线程个数,可以设置为 -1,这样可以充分使用机器的所有处理器,并行数量越多,有利于缩短调参时间;
  • iid:如果设置为True,则默认假设数据在每折中具有相同地分布,并且最小化的损失是每个样本的总损失,而不是每折的平均损失。简单点说,就是如果你可以确定 cv 中每折数据分布一致就设置为 True,否则设置为 False;
  • cv:交叉验证的折数,默认为3折;

常用属性:

  • cv_results_:用来输出cv结果的,可以是字典形式也可以是numpy形式,还可以转换成DataFrame格式
  • best_estimator_:通过搜索参数得到的最好的估计器,当参数refit=False时该对象不可用
  • best_score_:float类型,输出最好的成绩
  • best_params_:通过网格搜索得到的score最好对应的参数
  • best_index_:对应于最佳候选参数设置的索引(cv_results_数组)。cv_results _ [‘params’] [search.best_index_]中的dict给出了最佳模型的参数设置,给出了最高的平均分数(search.best_score_)。
  • scorer_:评分函数
  • n_splits_:交叉验证的数量
  • refit_time_:refit所用的时间,当参数refit=False时该对象不可用

常用函数:

  • decision_function(X):返回决策函数值(比如svm中的决策距离)
  • fit(X,y=None,groups=None,fit_params):在数据集上运行所有的参数组合
  • get_params(deep=True):返回估计器的参数
  • inverse_transform(Xt):Call inverse_transform on the estimator with the best found params.
  • predict(X):返回预测结果值(0/1)
  • predict_log_proba(X): Call predict_log_proba on the estimator with the best found parameters.
  • predict_proba(X):返回每个类别的概率值(有几类就返回几列值)
  • score(X, y=None):返回函数
  • set_params(**params):Set the parameters of this estimator.
  • transform(X):在X上使用训练好的参数

属性grid_scores_已经被删除,改用:

means = grid_search.cv_results_['mean_test_score']
params = grid_search.cv_results_['params']

  

 举例:

使用多评价指标,必须设置refit参数,可以显示多指标的结果,但是最后显示最佳的参数时候必须指定一个指标,详解:解决方法

param_test2 = { 'max_depth':[3,4,5,6], 'min_child_weight':[0.5,1,1.5]}
scorers = {
'precision_score': make_scorer(precision_score),
'recall_score': make_scorer(recall_score),
'accuracy_score': make_scorer(accuracy_score)
}
gsearch2 = GridSearchCV(estimator = XGBClassifier(
learning_rate =0.1, n_estimators=270, max_depth=4,min_child_weight=1, gamma=0, subsample=0.8,\
colsample_bytree=0.8, objective= 'binary:logistic', nthread=4,\
scale_pos_weight=1, seed=27),\
param_grid = param_test1,scoring=scorers,refit ='precision_score',n_jobs=4,iid=False, cv=5)
gsearch2.fit(x_train_resampled,y_train_resampled)

查看最佳结果:

>>>gsearch2.best_params_,gsearch2.best_score_,gsearch2.cv_results_['mean_test_precision_score'],gsearch2.cv_results_['params']

({'max_depth': 9, 'min_child_weight': 1},
0.8278796760710192,
array([0.79985227, 0.80330522, 0.80645782, 0.8223829 , 0.81170396,
0.80891565, 0.82691152, 0.82032078, 0.82220572, 0.82787968,
0.82439509, 0.81863326]),
[{'max_depth': 3, 'min_child_weight': 1},
{'max_depth': 3, 'min_child_weight': 3},
{'max_depth': 3, 'min_child_weight': 5},
{'max_depth': 5, 'min_child_weight': 1},
{'max_depth': 5, 'min_child_weight': 3},
{'max_depth': 5, 'min_child_weight': 5},
{'max_depth': 7, 'min_child_weight': 1},
{'max_depth': 7, 'min_child_weight': 3},
{'max_depth': 7, 'min_child_weight': 5},
{'max_depth': 9, 'min_child_weight': 1},
{'max_depth': 9, 'min_child_weight': 3},
{'max_depth': 9, 'min_child_weight': 5}])

查看交叉验证的中间结果:

pd.DataFrame(gsearch2.cv_results_)

 画图显示最佳参数:

grid_visualization = []
for grid_pair in gsearch2.cv_results_['mean_test_precision_score']:
grid_visualization.append(grid_pair)
grid_visualization = np.array(grid_visualization)
grid_visualization.shape = (4,3)
sns.heatmap(grid_visualization,annot=True,cmap='Blues',fmt='.3f')
plt.xticks(np.arange(3)+0.5,gsearch2.param_grid['min_child_weight'])
plt.yticks(np.arange(4)+0.5,gsearch2.param_grid['max_depth'])
plt.xlabel('min_child_weight')
plt.ylabel('max_depth')

  

参考文献:

【1】集成树模型GridSearchCV,stacking

【2】python机器学习库sklearn——参数优化(网格搜索GridSearchCV、随机搜索RandomizedSearchCV、hyperopt)

【3】XGBoost参数调优完全指南

【4】使用GridSearchCV进行网格搜索(比较全)

【5】当GridSearch遇上XGBoost 一段代码解决调参问题

集成树模型使用自动搜索模块GridSearchCV,stacking的更多相关文章

  1. 调参侠的末日? Auto-Keras 自动搜索深度学习模型的网络架构和超参数

    Auto-Keras 是一个开源的自动机器学习库.Auto-Keras 的终极目标是允许所有领域的只需要很少的数据科学或者机器学习背景的专家都可以很容易的使用深度学习.Auto-Keras 提供了一系 ...

  2. node.js零基础详细教程(7.5):mongo可视化工具webstorm插件、nodejs自动重启模块Node Supervisor(修改nodejs后不用再手动命令行启动服务了)

    第七章 建议学习时间4小时  课程共10章 学习方式:详细阅读,并手动实现相关代码 学习目标:此教程将教会大家 安装Node.搭建服务器.express.mysql.mongodb.编写后台业务逻辑. ...

  3. Java开源生鲜电商平台-搜索模块的设计与架构(源码可下载)

    Java开源生鲜电商平台-搜索模块的设计与架构(源码可下载) 说明:搜索模块针对的是买家用户,在找菜品找的很费劲下的一种查询方面.目前也是快速的检索商品. 对于移动端的APP买家用户而言,要求的速度在 ...

  4. React-Native 之 GD (十五)搜索模块 及 设置模块

    1.搜索模块 GDSearch.js /** * 搜索页面 */ import React, { Component } from 'react'; import { StyleSheet, Text ...

  5. 天津政府应急系统之GIS一张图(arcgis api for flex)讲解(八)资源搜索模块

    config.xml文件的配置如下: <widget label="资源搜索" icon="assets/images/public_impact_over.png ...

  6. 天津政府应急系统之GIS一张图(arcgis api for flex)讲解(六)地图搜索模块

    config.xml文件的配置如下: <widget label="地图搜索" icon="assets/images/emergency_resource_ove ...

  7. 使用AJAX做关键字查询:输入框变化自动搜索、无刷新页面;

    使用AJAX做关键字查询要求:1.无刷新页面2.输入框变化自动搜索 <style type="text/css"> .k{ width:150px; height:30 ...

  8. Winform开发框架之通用自动更新模块(转)

    在网络化的环境中,特别是基于互联网发布的Winform程序,程序的自动更新功能是比较重要的操作,这样可以避免挨个给使用者打电话.发信息通知或者发送软件等,要求其对应用程序进行升级.实现程序的自动更新, ...

  9. DevExpress.LookUpEdit控件实现自动搜索定位功能 兼使用方法(looUpEdit可编辑)

    DevExpress.LookUpEdit 使用方法 设置可手动输入 this.LookUpEdit1.Properties.TextEditStyle = DevExpress.XtraEditor ...

随机推荐

  1. Shell find命令详解

    查找文件find ./ -type f 查找目录find ./ -type d 查找名字为test的文件或目录find ./ -name test 查找名字符合正则表达式的文件,注意前面的‘.*’(查 ...

  2. 题目1161:Repeater(规律输出图形)

    题目1161:Repeater 题目链接:http://ac.jobdu.com/problem.php?pid=1161 具体分析:https://github.com/zpfbuaa/JobduI ...

  3. [原]git的使用(一)---建立本地仓库、add和commit、status和git diff、版本回退使用git reset

    在window下已经安装了git的环境 1.建立本地仓库 mkdir   test     #建立test目录 cd   test        #进入目录 git  init           # ...

  4. laravel 查看sql

    方法一: 我们有时候想测试一段代码生产的 SQL 语句,比如: 我们想看 App\User::all(); 产生的 SQL 语句,我们简单在 routes.php 做个实验即可: //app/Http ...

  5. SVN服务端安装

    1 首先安装SVN和Subversion. 安装文件可自行百度. 2 在服务端创建版本库. 我的安装目录是c:\Program Files(x86)\Subversion. 安装完成后在安装目录下sh ...

  6. Android sd卡log日志

    import android.os.Environment; import android.util.Log; import java.io.File; import java.io.FileOutp ...

  7. #if 和 #ifdef 条件编译注意

    之前写程序很少用到这两个条件编译,只是在头文件的开头使用过 #ifdef ....<CODE>....  #endif,他是防止头文件被重复包含,导致的变量被多处声明或定义. 最近写程序发 ...

  8. java 中常见的一些错误

    1.NosuchMethodError java 类中找不到该方法! 可能该类所在的同一个包下有一个相同的相同的类,然后那个类中没有我们所要调用的类. 解决方法:若那个类不需要,可以删除class! ...

  9. Oracle Function:TO_CHAR

    Description The Oracle/PLSQL TO_CHAR function converts a number or date to a string.将数字转换为日期或字符串 Syn ...

  10. MySQL复制日常维护与管理

    一.复制一些常见设置 1.mysql复制启动时参数: mysql启动时的参数包括:master_host,master_port,master_user,master_password,master_ ...