機械学習-ランダムSearcCV、GridSearchCVクリーンアップ、実践、最適なスーパーパラメータ


RandomizedSearchCVとは?


これは分類器を決定し、分類器の最適なスーパーパラメータを探す方法の一つである.
与えられた問題の分類器でモデルを構築した後,性能を改善するために調整すると,すべてのパラメータを一つ一つ調整し,適切な組合せを見つけることが困難になるため,誤差値が最小のスーパーパラメータを見つけることができる良いライブラリである.
CVの名前と同様に、Cross Validationを独自に行って、最も有効なスーパーパラメータ値を得ることもできます.

機能:


調整するパラメータを指定してパラメータ値の範囲を決定し、n iter値を指定して対応する数でランダムに組み合わせて繰り返し、最終的な最適パラメータ値を得る.

サンプルモデルを作成するには

import pandas as pd

# 데이터셋 불러오기
df = pd.read_csv('WA_Fn-UseC_-Telco-Customer-Churn.csv')
df

RandomForestを使用してKlombeのキャリアメンバーデータをロードし、Hyperパラメータを調整してパフォーマンスを改善する例を表示します.目標は、最近1ヶ月以内に脱退するかどうかを判断する「Chern」です.
# 타겟 설정 - 회원 탈퇴 여부
target = 'Churn'

# 타겟의 분포 확인
df[target].value_counts(normalize = True)
[output]

No     0.73463
Yes    0.26537
Name: Churn, dtype: float64
脱退していない会員は73%,脱退していない会員は26%で,アンバランスな等級であることを確認し,class weight="balanced"を共に入力した後,パラメータ調整のない基本ランダムforestモデルの作成を行った.

パラメータを調整せずにRandomForestを作成

from sklearn.model_selection import train_test_split
from category_encoders import OrdinalEncoder
from sklearn.pipeline import make_pipeline
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import f1_score, confusion_matrix

train, test = train_test_split(df, test_size = 0.4, random_state = 2)
features = df.drop(columns = target).columns

X_train = train[features]
y_train = train[target]
X_test = test[features]
y_test = test[target]


#파이프라인 생성 - 인코더 / 분류기 한번에 넣기
pipe = make_pipeline(
    OrdinalEncoder(),  # 수치형으로 따로 고려없이 변경진행
    RandomForestClassifier(class_weight= 'balanced') # class weight만 blanced로 넣어 진행해본다.
)

# train set에 학습
pipe.fit(X_train, y_train)

# 정확도 점검
print('검증 정확도:',pipe.score(X_test, y_test))
y_test_pred = pipe.predict(X_test)
print('F1:',f1_score(y_test, y_test_pred, pos_label = 'Yes'))
[output]

검증 정확도: 0.7892122072391767
F1: 0.4807692307692308
検査精度は78で、まあまあのように見えますが、f 1 scoreは0.5未満の低点です.これを高めるために,ランダムSearchCVにより最適なスーパーパラメータを見つけることを試みた.

ランダムSearchCVを使用して最適なパラメータを検索するモデルの作成

%%time
from sklearn.model_selection import RandomizedSearchCV


pipe = make_pipeline(
    OrdinalEncoder(),  
    RandomForestClassifier( class_weight= 'balanced')
)

# 최적값을 구하고 싶은 파라미터를 정리 
dists = {
    'randomforestclassifier__max_depth' : [3,5,10,15],
    'randomforestclassifier__max_features' : [3,5,10],
    'randomforestclassifier__n_estimators' : [80, 100, 150, 200]
}

# RandomizedSearchCV 작성
clf1= RandomizedSearchCV(
    pipe,
    param_distributions=dists, # 파라미터 입력
    n_iter = 500,   # random search 탐색 횟수
    cv = 5,        # cv 검증을 위한 분할 검증 횟수
    scoring='accuracy',  # 오차 평가방법
    verbose=1,     # 진행상황
    random_state = 2
  )

clf1.fit(X_train, y_train)
[output]
Fitting 5 folds for each of 48 candidates, totalling 240 fits
CPU times: user 2min 54s, sys: 767 ms, total: 2min 55s
Wall time: 2min 55s
  • ビットに示すように、パイプを挿入する場合、要素(エンコーダやEstimatorなど)ごとにスーパーパラメータ値を設定し、RandomizedSearchCVを行います.n iter,cv値とともに探すパラメータ値が多ければ多いほど時間が長くなる.
  • 採点により、ランダム測定時の重点表示誤差を設定することができ、必要に応じて解決する問題を変更することができる.
  • 結果の生成に要する時間は、
  • %の時間で決定される.時間効率に基づいてGridSearchCVと比較した.
  • from sklearn.metrics import accuracy_score
    print('최적 하이퍼파라미터: ', clf1.best_params_)
    y_test_pred = clf1.predict(X_test)
    print('검증 정확도:', clf1.best_score_)
    print('F1:',f1_score(y_test, y_test_pred, pos_label = 'Yes'))
    [output]
    
    최적 하이퍼파라미터:  {'randomforestclassifier__n_estimators': 80, 'randomforestclassifier__max_features': 3,'randomforestclassifier__max_depth': 3}
    검증 정확도: 0.7893491124260356
    F1: 0.5123558484349258
    最適なスーパーパラメータは.best paramsで確認できます.さらにclfには、最適なパラメータを含む分類器が含まれている.ベストスコア(上が正しい)のメトリックの最高パフォーマンス値をbest scoreで取得できます.
    RandomizedSearchCVフォーカスによる精度Scoreの性能が大きく向上したとは言えないが,f 1 Scoreではより包括的な性能が見られ,より大きな向上が見られる.

    GridSearchCVとは?


    Ranomized SearchCVと同様に,最大の違いはパラメータ範囲内のランダム選択ではないことである.RandomizedSearchCVはn iterによってランダム試行の数を制御できるが,GridSearchCVは全範囲をすべて組み合わせて最適パラメータを探すことができる.

    機能:


    パフォーマンスの改善では、Randomizedよりも優れた組み合わせを見つけることができますが、時間的には効率が大幅に低下します.いずれにしても、すべての組み合わせの性能を確認しなければならないので、そんな不便なところがあります.だから私は実はRandomizedをもっとよく使っています.

    サンプルモデルを作成するには


    GridSearchCVで最適なパラメータを検索するモデルの作成

    %%time
    
    from sklearn.model_selection import GridSearchCV
    
    pipe = make_pipeline(
        OrdinalEncoder(),  
        RandomForestClassifier( class_weight= 'balanced')
    )
    
    # 최적값을 구하고 싶은 파라미터를 정리 
    dists = {
        'randomforestclassifier__max_depth' : [3,5,10,15],
        'randomforestclassifier__max_features' : [3,5,10],
        'randomforestclassifier__n_estimators' : [80, 100, 150, 200]
    }
    
    # RandomizedSearchCV 작성
    grid= GridSearchCV(
        pipe,
        param_grid=dists, # 파라미터 입력
        cv = 5,        # cv 검증을 위한 분할 검증 횟수
        scoring='accuracy',  # 오차 평가방법
        verbose=1,     # 진행상황
      )
    
    grid.fit(X_train, y_train)
    [output]
    
    Fitting 5 folds for each of 48 candidates, totalling 240 fits
    CPU times: user 3min 1s, sys: 849 ms, total: 3min 1s
    Wall time: 3min 2s
    グリッド検索とランダム検索の条件は同じです.ランダム調査とは異なり,n iterなしですべての条件を行い,最適パラメータを探す方法である.時間的にはわずかな違いですが、ランダムな調査よりも時間がかかります.次に、パフォーマンスがどれだけ改善されたかを見てみましょう.
    from sklearn.metrics import accuracy_score
    print('최적 하이퍼파라미터: ', grid.best_params_)
    y_test_pred = grid.predict(X_test)
    print('검증 정확도:', grid.best_score_)
    print('F1:',f1_score(y_test, y_test_pred, pos_label = 'Yes'))
    최적 하이퍼파라미터:  {'randomforestclassifier__max_depth': 15, 'randomforestclassifier__max_features': 3, 'randomforestclassifier__n_estimators': 200}
    검증 정확도: 0.7888757396449704
    F1: 0.5240384615384616
    スーパーパラメータも変更され、f 1のスコアも上昇していることが確認された.検証精度(精度)はやや低下したが,random stateが固定されていないことを考慮すると,f 1スコアの上昇部分は我々が必要とする性能改善に近い.

    ランダムSearchCV/GridSearchCVの適用


    RandomizedSearchCV:GridSearchよりも時間効率が高い.データ量が多く、大量のパラメータ調整が必要な場合に有効です.
    GridSearchCV:データ量が多く、調整が必要なパラメータが多い場合は効率が低下します.すべてのパラメータを組み合わせてパフォーマンスを改善する必要がある場合に使用するのが適切です.