【sklearn】網格搜索 from sklearn.model_selection import GridSearchCV


      GridSearchCV用於系統地遍歷模型的多種參數組合,通過交叉驗證確定最佳參數。

1.GridSearchCV參數   

# 不常用的參數

  • pre_dispatch
    • 沒看懂

  • refit    
    • 默認為True
    • 在參數搜索參數后,用最佳參數的結果fit一遍全部數據集
  • iid                 
    • 默認為True
    • 各個樣本fold概率分布一致,誤差估計為所有樣本之和

# 常用的參數

  • cv
    • 默認為3
    • 指定fold個數,即默認三折交叉驗證
  • verbose
    • 默認為0
    • 值為0時,不輸出訓練過程;值為1時,偶爾輸出訓練過程;值>1時,對每個子模型都輸出訓練過程
  • n_jobs
    • cpu個數
    • 值為-1時,使用全部CPU;值為1時,使用1個CPU;值為2時,使用2個CPU
  • estimator       
    • 分類器
  • param_grid    
    • 參數范圍,值為列表/字典
  • scoring

2.常用屬性  

  • best_score_
    • 最佳模型下的分數
  • best_params_
    • 最佳模型參數
  • grid_scores_
    • 模型不同參數下交叉驗證的平均分
  • cv_results_   具體用法
    • 模型不同參數下交叉驗證的結果
  • best_estimator_
    • 最佳分類器

注:grid_scores_在sklearn0.20版本中將被刪除。使用cv_results_替代


3.常用函數

  • score(x_test,y_test)
    • 最佳模型在測試集下的分數


4.例子

  1 # -*- coding: utf-8 -*-
  2 """
  3 # 數據:20類新聞文本
  4 # 模型:svc
  5 # 調參:gridsearch
  6 """
  7 ### 加載模塊
  8 import numpy as np
  9 import pandas as pd
 10 
 11 ### 載入數據
 12 from sklearn.datasets import fetch_20newsgroups                          # 20類新聞數據
 13 news = fetch_20newsgroups(subset='all')                                  # 生成20類新聞數據
 14 
 15 ### 數據分割
 16 from sklearn.cross_validation import train_test_split
 17 X_train, X_test, y_train, y_test = train_test_split(news.data[:300],
 18                                                     news.target[:300],
 19                                                     test_size=0.25,      # 測試集占比25%
 20                                                     random_state=33)     # 隨機數
 21 ### pipe-line
 22 from sklearn.feature_extraction.text import TfidfVectorizer              # 特征提取
 23 from sklearn.svm import SVC                                              # 載入模型
 24 from sklearn.pipeline import Pipeline                                    # pipe_line模式
 25 clf = Pipeline([('vect', TfidfVectorizer(stop_words='english', analyzer='word')),
 26                 ('svc', SVC())])
 27 
 28 ### 網格搜索
 29 from sklearn.model_selection import GridSearchCV
 30 parameters = {'svc__gamma': np.logspace(-1, 1)}                           # 參數范圍(字典類型)
 31 
 32 gs = GridSearchCV(clf,          # 模型
 33                   parameters,   # 參數字典
 34                   n_jobs=1,     # 使用1個cpu
 35                   verbose=0,    # 不打印中間過程
 36                   cv=5)         # 5折交叉驗證
 37 
 38 gs.fit(X_train, y_train)        # 在訓練集上進行網格搜索
 39 
 40 ### 最佳參數在測試集上模型分數
 41 print("best:%f using %s" % (gs.best_score_,gs.best_params_))
 42 
 43 ### 測試集下的分數
 44 print("test datasets score" % gs.score(X_test, y_test))
 45 
 46 ### 模型不同參數下的分數
 47 # 方式一(0.20版本將刪除)
 48 print(gs.grid_scores_)
 49 
 50 # 方式二(0.20推薦的方式)
 51 means = gs.cv_results_['mean_test_score']
 52 params =  gs.cv_results_['params']
 53 
 54 for mean, param in zip(means,params):
 55     print("%f with: %r" % (mean,param))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM