用 Grid Search 對 SVM 進行調參
上一次用了驗證曲線來找最優超引數。
今天來看看網格搜尋(grid search),也是一種常用的找最優超引數的演算法。
網格搜尋實際上就是暴力搜尋:
首先為想要調參的引數設定一組候選值,然後網格搜尋會窮舉各種引數組合,根據設定的評分機制找到最好的那一組設定。
以支援向量機分類器 SVC 為例,用 GridSearchCV 進行調參:
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.svm import SVC
1. 匯入資料集,分成 train 和 test 集:
digits = datasets.load_digits()
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)
2. 備選的引數搭配有下面兩組,並分別設定一定的候選值:
例如我們用下面兩個 grids:
kernel=’rbf’, gamma, ‘C’
kernel=’linear’, ‘C’
tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],
'C': [1, 10, 100, 1000]},
{'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]
3. 定義評分方法為:
scores = ['precision' , 'recall']
4. 呼叫 GridSearchCV,
將 SVC(), tuned_parameters, cv=5
, 還有 scoring 傳遞進去,
用訓練集訓練這個學習器 clf,
再呼叫 clf.best_params_
就能直接得到最好的引數搭配結果,
例如,在 precision 下,
返回最好的引數設定是:{'C': 10, 'gamma': 0.001, 'kernel': 'rbf'}
還可以通過 clf.cv_results_
的 ‘params’,’mean_test_score’,看一下具體的引數間不同數值的組合後得到的分數是多少:
結果中可以看到最佳的組合的分數為:0.988 (+/-0.017)
還可以通過 classification_report
列印在測試集上的預測結果 clf.predict(X_test)
與真實值 y_test
的分數:
for score in scores:
print("# Tuning hyper-parameters for %s" % score)
print()
# 呼叫 GridSearchCV,將 SVC(), tuned_parameters, cv=5, 還有 scoring 傳遞進去,
clf = GridSearchCV(SVC(), tuned_parameters, cv=5,
scoring='%s_macro' % score)
# 用訓練集訓練這個學習器 clf
clf.fit(X_train, y_train)
print("Best parameters set found on development set:")
print()
# 再呼叫 clf.best_params_ 就能直接得到最好的引數搭配結果
print(clf.best_params_)
print()
print("Grid scores on development set:")
print()
means = clf.cv_results_['mean_test_score']
stds = clf.cv_results_['std_test_score']
# 看一下具體的引數間不同數值的組合後得到的分數是多少
for mean, std, params in zip(means, stds, clf.cv_results_['params']):
print("%0.3f (+/-%0.03f) for %r"
% (mean, 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()
相關閱讀:
推薦閱讀
歷史技術博文連結彙總
也許可以找到你想要的
[入門問題][TensorFlow][深度學習][強化學習][神經網路][機器學習][自然語言處理][聊天機器人]