python sklearn包——grid search筆記
阿新 • • 發佈:2019-02-18
Preface:演算法不夠好,需要除錯引數時必不可少。比如SVM的懲罰因子C,核函式kernel,gamma引數等,對於不同的資料使用不同的引數,結果效果可能差1-5個點,sklearn為我們提供專門除錯引數的函式grid_search。
在sklearn中以API的形式給出介紹。在離線包中函式較多,但常用為GridSearchCV()這個函式。
1.GridSearchCV:
看例子最為容易懂得使用其的方法。
sklearn包中介紹的例子:
from __future__ import print_function 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 print(__doc__) # 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 # Split the dataset in two equal parts X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.5, random_state=0) # Set the parameters by cross-validation tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4], 'C': [1, 10, 100, 1000]}, {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}] scores = ['precision', 'recall'] for score in scores: print("# Tuning hyper-parameters for %s" % score) print() clf = GridSearchCV(SVC(C=1), tuned_parameters, cv=5, scoring='%s_weighted' % score) 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()
其中,將引數放在列表中
tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4], 'C': [1, 10, 100, 1000]}, {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]建立分類器clf時,呼叫GridSearchCV()函式,將上述引數列表的變數傳入函式。並且可傳入交叉驗證cv引數,設定為5折交叉驗證。對訓練集訓練完成後呼叫best_params_變數,打印出訓練的最佳引數組。
Figure :執行結果
可以看出,其得出最佳引數組字典,還有每一次用引數組進行訓練得出的得分。最後在測試集上,給出10個類別的測試報告,對於類別0,RPF都為1,。。。。這裡使用sklearn.metrics下的classification_report()函式即可,輸入測試集真實的結果和預測的結果即返回每個類別的準確率召回率F值以及巨集平均值。
對於SVM分類器,這裡只列出線性核和RBF核,其中線性核不必用gamma這個引數,RBF核可用不同懲罰值C和不同的gamma值作為組合。上述列出的結果即可看出有哪些組合。這裡的結果是RBF核,懲罰項為10,gamma值為0.001效果最佳。滷煮以為RBF核是比較好的,但是在最近的學習中,確實是不一定,用了線性核效果更好些,但選訓練非常慢,資料集不一樣效果差很多吧,可能。