2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

モデルのチューニング-ハイパーパラメータチューニング(Hyperparameter Tuning)

2
Posted at

ハイパーパラメータ(Hyperparameter)とは

モデルをフィッティングする前に指定しなければならないパラメータをハイパーパラメータです。
つまり、モデルのフィッティングによって明示的に学習することができないパラメータです。

例えば、

  • 線形回帰:パラメータ
  • リッジ/ラッソ回帰:アルファ値
  • k-NN:n

などがハイパーパラメータです。

ハイパーパラメータチューニング(Hyperparameter Tuning)

ハイパーパラメータをチューニングするには以下が必要になります。

  • 多数の異なるハイパーパラメータ値を試す
  • すべてのパラメータを別々にフィットさせる
  • それぞれの性能を見る
  • 最も性能の良いものを選ぶ
  • 交差検証が不可欠

GridSearchCV

ハイパーパラメータチューニング手法として、グリッドサーチ(Grid Search)があります。
sklearn.model_selectionモジュールのGridSearchCVクラスで処理できます。

from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV

c_space = np.logspace(-5, 8, 15)
param_grid = {'C': c_space}

logreg = LogisticRegression()

logreg_cv = GridSearchCV(estimator=logreg, param_grid=param_grid, cv=5)

# Fit it to the data
logreg_cv.fit(X, y)

print("Best Logistic Regression Parameters: {}".format(logreg_cv.best_params_)) 
print("Best score is {}".format(logreg_cv.best_score_))

出力:

Best Logistic Regression Parameters: {'C': 3.727593720314938}
Best score is 0.7708333333333334

RandomizedSearchCV

大きなハイパーパラメータ空間の検索や、複数のハイパーパラメータを扱う場合、GridSearchCVの計算量が多くなります。
その場合RandomizedSearchCVを使用します。
指定された確率分布から、一定数のハイパーパラメータ設定をサンプリングします。

from scipy.stats import randint
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import RandomizedSearchCV

param_dist = {"max_depth": [3, None],
              "max_features": randint(1, 9),
              "min_samples_leaf": randint(1, 9),
              "criterion": ["gini", "entropy"]}

tree = DecisionTreeClassifier()

tree_cv = RandomizedSearchCV(tree, param_dist, cv=5)

# Fit it to the data
tree_cv.fit(X, y)

print("Best Decision Tree Parameters: {}".format(tree_cv.best_params_))
print("Best score is {}".format(tree_cv.best_score_))

出力:

Best Decision Tree Parameters: {'criterion': 'gini', 'max_depth': 3, 'max_features': 5, 'min_samples_leaf': 2}
Best score is 0.7395833333333334
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?