機器學習面試題集 - 超參數調優

超參數搜索算法一般包括哪幾個要素

目標函數

搜索範圍

算法的其他參數


超參數有哪些調優方法?

網格搜索

給出一個搜索範圍後,遍歷所有點,找出最優值

缺點:耗時

對策:將搜索範圍和步長先設置的大一些,鎖定最優值的範圍。

    再逐漸縮小範圍和步長,更精確的確定最優值

缺點:可能會錯過全局最優值

隨機搜索

給定一個搜索範圍後,從中隨機的選擇樣本點。

缺點:可能會錯過全局最優值

貝葉斯優化算法

通過學習目標函數的形狀,找到影響最優值的參數。

 算法:首先根據先驗分佈,假設一個蒐集函數。再用每個新的樣本點,更新目標函數的先驗分佈。由後驗分佈得到全局最值可能的位置

 缺點:容易陷入局部最優值,因爲找到了一個局部最優值,會在該區域不斷採樣

 對策:在還未取樣的區域進行探索,在最可能出現全局最值的區域進行採樣

下面來具體看看如何用 網格搜索(grid search) 對 SVM 進行調參。

網格搜索實際上就是暴力搜索:
首先爲想要調參的參數設定一組候選值,然後網格搜索會窮舉各種參數組合,根據設定的評分機制找到最好的那一組設置。


以支持向量機分類器 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()

相關文章:

用驗證曲線 validation curve 選擇超參數
爲什麼要用交叉驗證
用學習曲線 learning curve 來判別過擬合問題


大家好!我是 Alice,歡迎進入 機器學習面試題集 系列!

這個系列會以《百面機器學習》的學習筆記爲主線,除了用導圖的形式提煉出精華,還會對涉及到的重要概念進行更深度的解釋,順便也梳理一下機器學習的知識體系。

歡迎關注我,一起交流學習!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章