LoginSignup
14
28

More than 3 years have passed since last update.

ロジスティック回帰(分類)とハイパーパラメータのチューニング

Last updated at Posted at 2019-05-22

はじめに

 乳癌の腫瘍が良性であるか悪性であるかを判定するためのウィスコンシン州の乳癌データセットについて、ロジスティック回帰とハイパーパラメータのチューニングにより分類器を作成する。データはsklearnに含まれるもので、データ数は569、そのうち良性は212、悪性は357、特徴量は30種類ある。

シリーズ

ロジスティック回帰とは

ベルヌーイ分布に従う変数の統計的回帰モデルの一種である。連結関数としてロジットを使用する一般化線形モデル (GLM) の一種でもある。1958年に David Cox が発表した。確率の回帰であり、統計学の分類に主に使われる。医学や社会科学でもよく使われる。
(wikipediaより)

ロジスティック回帰のハイパーパラメータ

詳細は以下を参照されたい。
sklearn.linear_model.LogisticRegression

ハイパーパラメータ 選択肢 default
penalty l1,l2 l2
dual bool型 False
tol float型 0.0001
C float型 1
fit_intercept bool型 True
intercept_scaling float型 1
class_weight 辞書型、balanced 1(全クラス)
random_state int型 None
solver newton-cg、lbfgs、liblinear、sag、saga liblinear
max_iter int型 100
multi_class ovr、multinomial、auto ovr
verbose int型 0
warm_start bool型 False
n_jobs int型、None None
l1_ratio float、None None

手順

  • 乳癌データの読み込み
  • 条件設定
  • トレーニングデータ、テストデータの分離
  • グリッドサーチ
  • ランダムサーチ
  • ハイパーパラメータをチューニングしない場合との比較 # pythonによる実装
%%time
import scipy.stats
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import RandomizedSearchCV
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score

#乳癌データの読み込み
cancer_data = load_breast_cancer()

#条件設定
max_score = 0
SearchMethod = 0
LR_grid = {LogisticRegression(): {"C": [10 ** i for i in range(-5, 6)],
                                  "random_state": [i for i in range(0, 101)]}}
LR_random = {LogisticRegression(): {"C": scipy.stats.uniform(0.00001, 1000),
                                    "random_state": scipy.stats.randint(0, 100)}}
#トレーニングデータ、テストデータの分離
train_X, test_X, train_y, test_y = train_test_split(cancer_data.data, cancer_data.target, random_state=0)

#グリッドサーチ
for model, param in LR_grid.items():
    clf = GridSearchCV(model, param)
    clf.fit(train_X, train_y)
    pred_y = clf.predict(test_X)
    score = f1_score(test_y, pred_y, average="micro")

    if max_score < score:
        max_score = score
        best_param = clf.best_params_
        best_model = model.__class__.__name__

#ランダムサーチ
for model, param in LR_random.items():
    clf =RandomizedSearchCV(model, param)
    clf.fit(train_X, train_y)
    pred_y = clf.predict(test_X)
    score = f1_score(test_y, pred_y, average="micro")

    if max_score < score:
        SearchMethod = 1
        max_score = score
        best_param = clf.best_params_
        best_model = model.__class__.__name__

if SearchMethod == 0:
    print("サーチ方法:グリッドサーチ")
else:
    print("サーチ方法:ランダムサーチ")
print("ベストスコア:{}".format(max_score))
print("モデル:{}".format(best_model))
print("パラメーター:{}".format(best_param))

#ハイパーパラメータを調整しない場合との比較
model = LogisticRegression()
model.fit(train_X, train_y)
score = model.score(test_X, test_y)
print("")
print("デフォルトスコア:", score)

結果

サーチ方法:ランダムサーチ

サーチ方法:ランダムサーチ
ベストスコア:0.965034965034965
モデル:LogisticRegression
パラメーター:{'C': 866.92427079018307, 'random_state': 56}

デフォルトスコア: 0.958041958042
Wall time: 11.5 s

おわりに

 ロジスティック回帰により約97%という高い正解率を得ることができた。計算時間が膨大になるため選択したパラメータは少なかったものの、ランダムサーチによりdefaultのハイパーパラメータによる値を上回ることができた。

14
28
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
14
28