sklearn中GridSearch的使用

2021-08-21 19:50:39 字數 2413 閱讀 4731

搞懂了k-fold,就可以聊一聊gridsearch啦,因為gridsearch預設引數就是3-fold的,如果沒有不懂cross-validation就很難理解這個.

gridsearch是為了解決調參的問題.比如向量機svm的常用引數有kernel,gamma,c等,手動調的話太慢了,寫迴圈也只能順序執行,不能並行.於是就出現了gridsearch.通過它,可以直接找出最優的引數.

param字典型別,它會將每個字典型別裡的字段所有的組合都輸入到分類器中執行.

tuned_parameters = [,

]

引數輸入之後,需要評估每組引數對應的模型的**能力.gridsearch就在資料集上做k-fold,然後求出每組引數對應模型的平均精確度.選出最優的引數.返回.

一般gridsearch只在訓練集上做k-fold並不會使用測試集.而是將測試集留在最後,當gridsearch選出最佳模型的時候,在使用測試集測試模型的泛化能力.

貼乙個sklearn上面的例子

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()

# 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 = [,

]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()

原文:

上面這個例子就符合一般的套路.例子中的svc是支援多分類的,其預設使用的是ovo的方式,如果需要改變,可以將引數設定為decision_function_shape=』ovr』,具體的可以參看svc的api文件.

Anaconda中sklearn包不全

起因 一開始在一台伺服器上單獨安裝了sklearn,用於訓練模型,生成pkl檔案。後來由於發現anaconda中整合了包含sklearn在內測好多安裝包,於是打算將程式移植到anaconda上,並且保留原先的模型pkl檔案。結果在除錯的時候發現了錯誤。主要是在載入pkl檔案的時候,出現錯誤。排查過程...

sklearn 中的 Pipeline 機制

管道機制在機器學習 演算法中得以應用的根源在於,引數集在新資料集 比如測試集 上的重複使用。管道機制實現了對全部步驟的流式化封裝和管理 streaming workflows with pipelines 注意 管道機制更像是程式設計技巧的創新,而非演算法的創新。接下來我們以乙個具體的例子來演示sk...

sklearn 中的 Pipeline 機制

from sklearn.pipeline import pipelinefrom pandas as pd from sklearn.cross validation import train test split from sklearn.preprocessing import labelen...