ML Custom Scoring 사용하기

snooby·2022년 11월 22일
2

🦾 ML

목록 보기
7/16
post-thumbnail

Sklearn에서 cv score 사용할 때, 많은 scoring이 있지만, 경우에 따라 직접 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

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))

make_scorer

  • make_scorer의 custom_scoring : custom scoring 함수
  • make_scorer의 greater_is_better : False는 score 값이 낮은게 좋음을 의미

참조 :https://wooono.tistory.com/204

profile
데이터를 가치있게 다루고 싶은 개발자 🐥

0개의 댓글