머신러닝/Cross Validation(k-fold)

Cross Validation (교차검증)

Stevelee_HMC 2022. 8. 25. 07:47

모델의 성능이 개선되었는지 , 셀프 검증이 필요할 때 교차검증을 통해 확인할 수 있다.

가장 심플하게 검증할 수 있는 방법을 제공하고자 한다.

 

한번에 여러개의 모델에 대한 교차검증을 통해 결과를 확인 가능하다.

 

from sklearn.model_selection import KFold

kfold = KFold(n_splits= 10)

### 10개로 fold를 나눈다.
score_list_cat_reg = []
score_list_xgb_reg = []



### 10개의 fold에서의 각 모델의 score값을 담는 list


def rmse(real , pred):
    score = np.sqrt(np.mean(np.square(real - pred)))
    
    return score


### 평가 메트릭 선언(커스터마이징)

 

kfold를 통한 모델별 성능 검증  아래 반복문에 정상적인 X_train ,y_train만 넣으면 

모델별 스코어를  확인 가능하다.

 

for train_idx , val_idx in kfold.split(X_train , y_train):
    
    X_tr , y_tr = X_train.iloc[train_idx] y_train.iloc[train_idx]
    X_val ,y_val = X_train.iloc[val_idx] , y_train.iloc[val_idx]
    
    ### X_train , y_train 에서 index를 임의로 10개를 나눠서 train , val idx로 정의하고 
    ### 검증용 train data인 tr과 validation data인 val을 만든다.
    
    model = CatBoostRegressor()
    model.fit(X_tr ,y_tr)
    pred_cat = model.predict(X_val)
    score_cat = rmse(y_val , pred_cat) 
    
    score_list_cat_reg.append(score_cat)
    
    ### catboost 모델을 활용한 검증 
     
    model = XGBRegressor()
    model.fit(X_tr ,y_tr)
    pred_xgb = model.predict(X_val)
    score_xgb = rmse(y_val , pred_xgb) 
    
    score_list_xgb_reg.append(score_xgb)

    ### xgboost 모델을 활용한 검증 
    


print(np.array(score_list_cat_reg).mean())
print(np.array(score_list_xgb_reg).mean())
### 각 모델별 성능 검증

 

그외 cross_validation 은 구글링을 통해 쉬운 예제를 확인할 수 있다.