오늘의 인기 글
최근 글
최근 댓글
Today
Total
05-14 00:01
관리 메뉴

우노

[ML] Sklearn cross_val_score Custom Scoring 사용하기 본문

AI/Machine Learning

[ML] Sklearn cross_val_score Custom Scoring 사용하기

운호(Noah) 2021. 1. 4. 14:58
  • Sklearn cross_val_score() 사용 시, 이미 존재하는 많은 scoring 방법들을 사용할 수 있지만
  • 경우에 따라 직접 scoring을 만들어 사용하고 싶을 때가 있다.
  • 이 때, 다음과 같이 Custom Scoring을 만들어 사용할 수 있다.

Custom Scoring 함수 생성

from sklearn.metrics import r2_score, mean_squared_error

def mean_absolute_percentage_error(y_test, y_pred):
    y_test, y_pred = np.array(y_test), np.array(y_pred)
    return np.mean(np.abs((y_test - y_pred) / y_test)) * 100

def custom_scoring(y_test, y_pred):

    rmse = np.sqrt(mean_squared_error(y_test, y_pred))
    r2 = r2_score(y_test, y_pred)
    mape = mean_absolute_percentage_error(y_test, y_pred)

    return mape

cross_val_score() 시 Custom Scoring 함수 사용

import xgboost as xgb
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.metrics import make_scorer

# 모델 객체 생성
model = xgb.XGBRegressor(learning_rate=0.1,
                                 max_depth=5,
                                 n_estimators=100)
# 상세 조정한 kfold 객체 생성
kfold = KFold(n_splits=10, shuffle = True, random_state=0)

# cross_val_score 진행
scores = cross_val_score(model , 
                        train_feature , 
                        train_target ,
                        cv=kfold,
                        n_jobs=-1,
                        scoring=make_scorer(custom_scoring,greater_is_better=False)
                        )

# 최종적으로 평균을 내어 정확도를 간단히 한다.
print('교차 검증별 정확도:',np.round(scores, 4))
print('평균 검증 정확도:', np.round(np.mean(scores), 4))
  • KFold 파라미터

    • n_splits : 몇 개의 fold를 사용할지
    • shuffle : fold 분할 전, 데이터를 무작위로 섞을지
    • random_state : fold 분할 후, fold를 그대로 유지할지
  • cross_val_score 파라미터

    • model : 모델객체
    • train_feature : Train data의 feature
    • train_target : Train data의 target
    • cv : 상세 조정한 kfold 객체
    • n_jobs : 병렬로 실행할 작업 수 (-1은 전부)
    • scoring : make_scorer 객체
      • make_scorer의 custom_scoring : custom scoring 함수
      • make_scorer의 greater_is_better : False는 score 값이 낮은게 좋음을 의미
Comments