[CodesSates] AI 부트캠프

Model Selection

웅탈 2021. 4. 15. 22:10

Model Selection

 

교차 검증 (Cross-validation)

 

- 데이터 셋이 부족할 때도 사용가능 / k개의 성능 결과를 통합하여 결과를 도출하기 때문에, 일반화된 모델 성능 평가 가능 (시계열 데이터에는 적합하지 않음)

 

- 최적화 : 훈련 데이터로 더 좋은 성능을 얻기 위해 모델을 조정하는 과정

- 일반화 : 학습된 모델이 처음 본 데이터에서 얼마나 좋은 성능을 낼수있는가

 

Randomized Search CV

 

- 검증하려는 하이퍼 파라미터들의 값 범위를 지정해주면 무작위로 값을 지정해 그 조합을 검증

 

# Randomized Search CV 예시

from scipy.stats import randint, uniform

pipe = make_pipeline(
    TargetEncoder(), 
    SimpleImputer(), 
    RandomForestRegressor(random_state=2)
)

dists = {
    'targetencoder__smoothing': [2.,20.,50.,60.,100.,500.,1000.], # int로 넣으면 error(bug)
    'targetencoder__min_samples_leaf': randint(1, 10),     
    'simpleimputer__strategy': ['mean', 'median'], 
    'randomforestregressor__n_estimators': randint(50, 500), 
    'randomforestregressor__max_depth': [5, 10, 15, 20, None], 
    'randomforestregressor__max_features': uniform(0, 1) # max_features
}

clf = RandomizedSearchCV(
    pipe, 
    param_distributions=dists, 
    n_iter=50, 
    cv=3, 
    scoring='neg_mean_absolute_error',  
    verbose=1,
    n_jobs=-1
)

clf.fit(X_train, y_train);


# 최적 파라미터 확인

print('최적 하이퍼파라미터: ', clf.best_params_)
print('MAE: ', -clf.best_score_)
최적 하이퍼파라미터:  {'simpleimputer__strategy': 'mean', 'selectkbest__k': 73, 'ridge__alpha': 10}
MAE:  18433.631324905822


# rank_test_score: 테스트 순위
# mean_score_time: 예측에 걸리는 시간
pd.DataFrame(clf.cv_results_).sort_values(by='rank_test_score').T

 

 

 

 

GridSearchCV

 

- 검증하려는 하이퍼 파라미터들의 수치를 정해주고 그 조합을 모두 검증 / 상대적으로 오래 걸림

 

 

GridSearchCV( model,       # estimator
            param_grid=,   # 찾고자하는 파라미터. dict형식
            cv= 2 or KFold(2),
            scoring=None,  #  Classification일때  'accuracy','f1'
                           #  Regression 일때 'neg_mean_squared_error','r2'...
                           
            n_jobs= 4,     # 병렬 처리갯수? -1은 전부)
            refit=True     # default가 True. 
                           # 좋은 estimator로 수정되어짐.
            )   


GCV=GridSErchCV( )         # 옵션.
GCV.fit( )                 # train_X, train_Y 
GCV.best_params_           # 좋은 파라미터를 보여줌.
GCV.best_score_            # 0.88 좋은 estimator로
                           # 교차검증된점수를 보여줌.

# 예측방법.1
model=GCV.best_estimator_  # 최적의 파라미터로 모델 생성
model.predict()            # refit=True이기때문에 좋은 estimator로
                           # 수정되어졌으므로 바로 예측에 적용할 수 있다.
# 예측방법2
GCV.predict( )             # test_X,  학습후 최적의 파라미터로 예측한다.

 

  • estimator : 적용 알고리즘 모델로 classifier, regressor, pipeline 등이 사용
  • param_grid : ket+리스트 값을 가지는 딕셔너리가 주어짐. estimator의 튜닝을 위해 파라미터명과 사용될 여러 파라미터 값을 지어
  • scoring : 예측 성능을 평가할 평가 방법을 지정, 문자열로 사이킷런의 성능평가 지표를 입력하나 별도의 함수 지정도 가능
  • refit : 기본값은 True이며 True로 생성시 가장 최적의 하이퍼 파라미터를 찾은 뒤 입력된 estimator 객체를 해당 하이퍼 파리미터로 재학습시킴

 

- 진행 표시바 표시

m.blog.naver.com/PostView.nhn?blogId=kiddwannabe&logNo=221275017358&proxyReferer=https:%2F%2Fwww.google.com%2F

 

파이썬 진행표시바 표시하기: tqdm

tqdm 라이브러리 5.0.0 이상의 버전에서는 tqdm_notebook이라는 명령어를 사용하지 못합니다. 그래서 명령...

blog.naver.com

 

'[CodesSates] AI 부트캠프' 카테고리의 다른 글

Feature Importances  (0) 2021.04.22
Choose Your ML Problems  (0) 2021.04.22
Evaluation Metrics for Classification  (0) 2021.04.14
Random Forests  (0) 2021.04.14
Decision Trees  (0) 2021.04.12