使用 GridSearchCV 同步調整 gamma 與 C
在上一個練習中,使用預設的 C 值 1 時,gamma 的最佳值是 0.001。這個練習中,你將用 GridSearchCV 尋找 C 與 gamma 的最佳組合。
和上一個練習一樣,2 與非 2 的手寫數字資料集已經載入,但這次已經分割為 X_train、y_train、X_test 和 y_test。即使交叉驗證會把訓練集再切分成數個部分,通常仍建議另外保留一個測試集,以確保交叉驗證的結果合理可靠。
本練習屬於課程
Python 中的線性分類器
練習說明
- 使用訓練集執行
GridSearchCV,找出最佳超參數。 - 列印最佳參數的數值。
- 列印測試集上的準確率(此資料並未參與交叉驗證過程)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Instantiate an RBF SVM
svm = SVC()
# Instantiate the GridSearchCV object and run the search
parameters = {'C':[0.1, 1, 10], 'gamma':[0.00001, 0.0001, 0.001, 0.01, 0.1]}
searcher = GridSearchCV(svm, ____)
____.fit(____)
# Report the best parameters and the corresponding score
print("Best CV params", searcher.best_params_)
print("Best CV accuracy", searcher.best_score_)
# Report the test accuracy using these best parameters
print("Test accuracy of best grid search hypers:", searcher.score(____))