scikit-learn - GridSearchCV でハイパーパラメータの最適値を探す
概要
scikit-learn でモデルのハイパーパラメータを GridSearchCV で探索する方法を紹介する。
基本的な使い方
GridSearchCV を使うと、指定したモデルのパラメータをグリッドサーチ (力まかせ探索) することができる。
1. GridSearchCV オブジェクトを作成する。
コンストラクタの主な引数
- estimator: モデル。(例えば SVC の場合、sklearn.svm.SVC オブジェクト)
- param_grid: 探索対象のパラメータ一覧
- cv: 交差検証の回数 (cv=5 の場合、1つのパラメータの組み合わせに対して、5分割交差検証を行う。)
param_grid 引数には辞書形式で探索するパラメータの値を渡す。
以下の場合、パラメータ kernel を2通り、パラメータ C を4通りの合計 通りを試すことになる。
2. グリッドサーチを実行する。
clf.fit() に学習データを渡すことでグリッドサーチが実行される。
3. 最も精度がよいモデルを取得する。
best_estimator_ 属性で最も精度がよかったパラメータのモデルを取得できる。
サンプルコード
parameters = {'kernel': ['linear', 'rbf'], 'C': [0.1, 1, 10, 100]}
import pandas as pd from sklearn import datasets from sklearn.model_selection import GridSearchCV, train_test_split from sklearn.svm import SVC # データセットを準備する。 iris = datasets.load_iris() x_train, x_test, y_train, y_test = train_test_split( iris.data, iris.target, test_size=0.25) # 試行するパラメータとその値 parameters = {'kernel': ['linear', 'rbf'], 'C': [0.1, 1, 10, 100]} # グリッドサーチする。 clf = GridSearchCV(SVC(gamma='scale'), parameters, cv=5, return_train_score=False, iid=False) clf.fit(x_train, y_train) # 最も精度がいいモデルを取得する。 best_clf = clf.best_estimator_ print('score: {:.2%}'.format(best_clf.score(x_test, y_test))) # score: 94.74%
グリッドサーチの結果を取得する。
グリッドサーチが完了すると、cv_results_ 属性で各パラメータごとの学習結果を確認できる。
辞書形式で情報が格納されているが、データフレームに変換すると、見やすく表示できる。
from pprint import pprint pprint(clf.cv_results_) cv_result = pd.DataFrame(clf.cv_results_) cv_result
各行があるパラメータでの学習結果を表す。
各列の意味は以下の通りである。
- mean_fit_time: 学習時間の平均
- mean_score_time: 推論時間の平均
- mean_test_score: テスト精度の平均
- param_
: 名前が であるパラメータの値 - params: 各パラメータの値
- rank_test_score: テスト精度の順位
- split
_test_score: 回目の交差検証のテスト精度 - std_fit_time: 学習時間の標準偏差
- std_score_time: 推論時間の標準偏差
- std_test_score: テスト精度の標準偏差
最も精度がよい結果の行は以下のように取得できる。
cv_result.loc[clf.best_index_]
最も精度がよいモデルの情報を取得する。
clf.best_estimator_ で最も精度がよいモデルを取得できる。
best_clf = clf.best_estimator_
clf.best_score_ で最も精度がよいモデルの精度を取得できる。
print('clf.best_score_', clf.best_score_) # clf.best_score_ 0.98
clf.best_params_ で最も精度がよいモデルのパラメータの値を取得できる。
print('clf.best_params_', clf.best_params_) # clf.best_params_ {'kernel': 'linear', 'C': 1}