'영화 관객수 예측 모델' 에서
K -Fold Validation 과 validation 데이터셋은 어떤 역할을 하는지 헷갈려서 정리하고자 포스팅
GradientBoostingRegressor
from sklearn.model_selection import KFold
from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor
kf = KFold(n_splits = 10, shuffle = True, random_state = 42) # 10 개의 Fold 를 만든다.
rmse_list = []
gb_pred = np.zeros((test.shape[0]))
for tr_idx, val_idx in kf.split(X, y) :
tr_x, tr_y = X.iloc[tr_idx], y.iloc[tr_idx]
val_x, val_y = X.iloc[val_idx], y.iloc[val_idx]
gbm.fit(tr_x, tr_y)
pred = np.expm1([0 if x < 0 else x for x in gbm.predict(val_x)])
sub_pred = np.expm1([0 if x < 0 else x for x in gbm.predict(X_test)])
rmse = np.sqrt(mean_squared_error(val_y, pred))
rmse_list.append(rmse)
gb_pred += (sub_pred / 10)
validation Data
- Training Set 으로 만들어진 모델의 성능을 측정하기 위해 사용된다.
- 여러 모델들 각각에 적용되어 성능을 측정하여, 최종 모델을 선정하기 위해 사용
- Test Set 은 최종 모델에 대한 성능을 측정
K-Fold Cross Validation

1. 기존 머신러닝과 동일하게 데이터를 Training set 과 Test set 으로 나눈다.
2. Training set 을 K 개의 Fold 로 나눈다.
3. 나눠진 K 개의 Fold 들을 다시 K 개로 쪼개고 K-1 개는 Training Data , 1 개는 Validation Data 로 사용한다.
( 이때 각 K 개 Fold 의 Validation Data 는 다르다. )
4. 모델을 생성한 후 예측을 진행하여 Validation Data 와 비교하여 에러값을 추출한다.
5. 이 시행을 K 개의 Fold 에 대하여 진행한다.
6. 검증된 결과의 평균을 측정한다. ( K 번의 정확도 결과를 평균 )
scikit learn 에서의 교차검증 예제 ( K=4 )
from sklearn.model_selection import KFold
import numpy as np
X = np.arange(16).reshape((8,-1))
y = np.arange(8).reshape((-1,1))
kf = KFold(n_splits=4)
for train_index, test_index in kf.split(X) :
print("TRAIN:", train_index, "TEST:",test_index) # 인덱스 출력
X_train,X_test = X[train_index], X[test_index]
y_train,y_test = y[train_index], y[test_index]


나뉜 Fold 중 하나를 살펴보면 다음과 같다.
TRAIN: [2 3 4 5 6 7] TEST: [0 1] # 인덱스
----------------------------------
[[ 4 5] # X_train 과 X_test
[ 6 7]
[ 8 9]
[10 11]
[12 13]
[14 15]] [[0 1]
[2 3]]
-------------
[[2] # y_train 과 y_test
[3]
[4]
[5]
[6]
[7]] [[0]
[1]]
- 4 개의 Fold 로 나눠야 하기 때문에 train / test 인덱스 값 4개 / 2 개임
'파이썬 > 머신러닝,딥러닝' 카테고리의 다른 글
| 모델 복잡도 제한을 위한 L1 , L2 규제 (0) | 2022.04.14 |
|---|---|
| Confusion matrix - Iris 데이터를 이용한 퍼셉트론 훈련 (0) | 2022.03.31 |
| 텐서플로우를 이용한 신경망 구현 예제 (0) | 2022.03.29 |
| Raschka Ch 1. Giving Computers the Ability to Learn from Data (0) | 2022.03.05 |
| Bagging - for 문을 이용하여 Bagging 구현 (0) | 2022.01.27 |