라일락 꽃이 피는 날

[Sklearn] Cross Validation 본문

데이터 분석/Python

[Sklearn] Cross Validation

eunki 2021. 5. 17. 17:32
728x90

Cross Validation

Cross Validation이란 모델을 평가하는 하나의 방법이다.

K-겹 교차검증(K-fold Cross Validation)을 많이 활용한다.

 

 

 

K-겹 교차검증

K-겹 교차 검증은 모든 데이터가 최소 한 번은 테스트셋으로 쓰이도록 한다.

아래의 그림을 보면, 데이터를 5개로 쪼개 매번 테스트셋을 바꿔나가는 것을 볼 수 있다.

 

 

 

 

K-Fold Cross Validation Set 만들기

from sklearn.model_selection import KFold

n_splits = 5
kfold = KFold(n_splits=n_splits, random_state=42)

X = np.array(df.drop('MEDV', 1))
Y = np.array(df['MEDV'])

lgbm_fold = LGBMRegressor(random_state=42)
i = 1
total_error = 0
for train_index, test_index in kfold.split(X):
    x_train_fold, x_test_fold = X[train_index], X[test_index]
    y_train_fold, y_test_fold = Y[train_index], Y[test_index]
    lgbm_pred_fold = lgbm_fold.fit(x_train_fold, y_train_fold).predict(x_test_fold)
    error = mean_squared_error(lgbm_pred_fold, y_test_fold)
    print('Fold = {}, prediction score = {:.2f}'.format(i, error))
    total_error += error
    i+=1
print('---'*10)
print('Average Error: %s' % (total_error / n_splits))

728x90