scikit_learn学习笔记十二——GridSearch,网格搜索

GridSearchCV 简介

GridSearchCV,自动调参,设置好相应参数,就能给出最优化的结果和参数。

数据量比较大的时候可以使用一个快速调优的方法——坐标下降。它其实是一种贪心算法:拿当前对模型影响最大的参数调优,直到最优化;再拿下一个影响最大的参数调优,如此下去,直到所有的参数调整完毕。这个方法的缺点就是可能会调到局部最优而不是全局最优,但是省时间省力,巨大的优势面前,还是试一试吧,后续可以再拿bagging再优化。回到sklearn里面的GridSearchCV,GridSearchCV用于系统地遍历多种参数组合,通过交叉验证确定最佳效果参数。

GridSearchCV

class sklearn.grid_search.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’)[source]

Deprecated since version 0.18: This module will be removed in 0.20. Use sklearn.model_selection.GridSearchCV instead.

  1. estimator
    选择使用的分类器,并且传入除需要确定最佳的参数之外的其他参数。

每一个分类器都需要一个scoring参数,或者score方法:

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

  1. param_grid
    需要最优化的参数的取值,值为字典或者列表,例如:
    param_grid =param_test1,
    param_test1 = {‘n_estimators’:range(10,71,10)}。

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

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

  4. cv=None

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

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

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

  3. return_train_score=’warn’
    如果“False”,cv_results_属性将不包括训练分数。

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

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

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

  • grid.fit():运行网格搜索
  • grid_scores_:给出不同参数情况下的评价结果
  • best_params_:描述了已取得最佳结果的参数的组合
  • best_score_:成员提供优化过程期间观察到的最好的评分

官网上贴例子

grid_search_digits.py

建立分类器clf时,调用GridSearchCV()函数,将上述参数列表的变量传入函数。并且可传入交叉验证cv参数,设置为5折交叉验证。对训练集训练完成后调用best_params_变量,打印出训练的最佳参数组。

from sklearn import datasets
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.svm import SVC

# Loading the Digits dataset
digits = datasets.load_digits()

# To apply an classifier on this data, we need to flatten the image, to
# turn the data in a (samples, feature) matrix:
n_samples = len(digits.images)
X = digits.images.reshape((n_samples, -1))
y = digits.target

# 将数据集分成训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.5, random_state=0)

# 设置gridsearch的参数
tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],
                     'C': [1, 10, 100, 1000]},
                    {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]

#设置模型评估的方法.如果不清楚,可以参考上面的k-fold章节里面的超链接
scores = ['precision', 'recall']

for score in scores:
    print("# Tuning hyper-parameters for %s" % score)
    print()

    #构造这个GridSearch的分类器,5-fold
    clf = GridSearchCV(SVC(), tuned_parameters, cv=5,
                       scoring='%s_weighted' % score)
    #只在训练集上面做k-fold,然后返回最优的模型参数
    clf.fit(X_train, y_train)

    print("Best parameters set found on development set:")
    print()
    #输出最优的模型参数
    print(clf.best_params_)
    print()
    print("Grid scores on development set:")
    print()
    for params, mean_score, scores in clf.grid_scores_:
        print("%0.3f (+/-%0.03f) for %r"
              % (mean_score, scores.std() * 2, params))
    print()

    print("Detailed classification report:")
    print()
    print("The model is trained on the full development set.")
    print("The scores are computed on the full evaluation set.")
    print()
    #在测试集上测试最优的模型的泛化能力.
    y_true, y_pred = y_test, clf.predict(X_test)
    print(classification_report(y_true, y_pred))
    print()

《scikit_learn学习笔记十二——GridSearch,网格搜索》 image.png

【以下转载】 sklearn中GridSearchCV如何设置嵌套参数
以adaboost为例,adaboost有自己的参数,他的base_estimator指向一个弱学习器,这个弱学习器也包含自己的参数,为了使用GridSearchCV我们需要使用嵌套参数。在sklearn中我们使用双下划线表示”__”,例如

from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.grid_search import GridSearchCV
iris = datasets.load_iris()
param_grid = {"base_estimator__criterion": ["gini", "entropy"],
          "base_estimator__splitter":   ["best", "random"],
          "n_estimators": [1, 2]}
dtc = DecisionTreeClassifier()
ada = AdaBoostClassifier(base_estimator=dtc)
X, y = datasets.make_hastie_10_2(n_samples=12000, random_state=1)
grid_search_ada = GridSearchCV(ada, param_grid=param_grid, cv=10)
grid_search_ada.fit(X, y)}
    原文作者:深思海数_willschang
    原文地址: https://www.jianshu.com/p/021bca117b22
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞