본문 바로가기

Python

[Python]교차검증을 위한 KFold 사용

머신러닝 모델 학습 과정 중 교차검증을 하기 위하여 학습 데이터셋을 나눠야 하는 일이 생깁니다.

이때 많은 사람들이 sklearn 패키지의 KFold cross-validator를 사용합니다.

 

class 

sklearn.model_selection.KFold(n_splits=2, random_state=None, shuffle=False)

 

Parameters

- n_splits(필수): 분할하려는 개수 

- shuffle(옵션): defalut=False이며, True일 때 데이터셋을 섞어서 분할

- random_state(옵션): shuffle이 True일 때 동일한 셔플을 발생시키는 시드 값

 

Example

from sklearn.model_selection import KFold
import numpy as np
import pandas as pd

np.random.seed(777)
df = pd.DataFrame(np.random.random((9,2)), columns=list('AB'))

kfold = KFold(n_splits=3, shuffle=True, random_state=7)
  
n_iter = 0
  
for train_index, test_index in kfold.split(df):

    n_iter += 1
    train = df.iloc[train_index]
    test = df.iloc[test_index]

    print("==============================")
    print("교차검증 번호: {0}".format(n_iter))

    print("학습 데이터")
    print(train)
    print("검증 데이터")
    print(test)
    print("==============================")
    
 
>>>   
==============================
교차검증 번호: 1
학습 데이터
          A         B
1  0.062036  0.459860
3  0.726989  0.768496
4  0.269205  0.644029
5  0.093373  0.079686
6  0.589614  0.343341
8  0.681779  0.552257
검증 데이터
          A         B
0  0.152664  0.302357
2  0.835253  0.926997
7  0.988876  0.626473
==============================
==============================
교차검증 번호: 2
학습 데이터
          A         B
0  0.152664  0.302357
1  0.062036  0.459860
2  0.835253  0.926997
4  0.269205  0.644029
6  0.589614  0.343341
7  0.988876  0.626473
검증 데이터
          A         B
3  0.726989  0.768496
5  0.093373  0.079686
8  0.681779  0.552257
==============================
==============================
교차검증 번호: 3
학습 데이터
          A         B
0  0.152664  0.302357
2  0.835253  0.926997
3  0.726989  0.768496
5  0.093373  0.079686
7  0.988876  0.626473
8  0.681779  0.552257
검증 데이터
          A         B
1  0.062036  0.459860
4  0.269205  0.644029
6  0.589614  0.343341
==============================