Model Selection 모듈
: 모델 구성 및 학습에 필요한 다양한 API 제공
- 데이터셋 분리
- 교차 검증 분할 및 평가
- 하이퍼 파라미터 튜닝
- etc...
데이터셋의 분할
- 왜 필요??
- 학습 데이터셋으로 평가 수행 시 부정확한(과도하게 높은) 평가 결과 발생
train_test_split() API
- 데이터셋의 분할(학습 / 테스트)을 쉽게 할 수 있는 API
- Argument
- test_size : 데스트 데이터셋의 비율
- train_size : 학습 데이터셋의 비율 (테스트와 학습 중 하나만 정해줘도 됨. 둘이 합쳐서 1)
- shuffle : 데이터셋 분리 전 미리 섞을지 여부
- random_state : 실행 시 마다 동일한 난수를 생성하기 위한 값
- Return
- 튜플 형태로 분할(학습 / 테스트)된 데이터 리턴
- API를 이용한 Iris 데이터셋 분할(학습 / 테스트)
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
iris = load_iris()
x_train, x_test, y_train, y_test = train_test_split(iris.data,
target,
test_size=0.3,
random_state=121)
- 분할된 데이터 중 학습 데이터를 이용해 학습
- 분할된 데이터 중 테스트 데이터를 이용해 성능 검증
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
dt_clf = DecisionTreeClassifier()
dt_clf.fit(x_train, y_train)
pred = dt_clf.predict(x_test)
print('predict accuracy: {}'.format(accuracy_score(y_test, pred)))
Validation(검증) 데이터 셋
- Training Data Set : 머신러닝 모델의 학습에 사용되는 데이터셋
- Testing Data Set : 학습된 머신러닝 모델의 서비스 가능 여부를 최종 확인하는 데이터셋
<------------------------------------------------------------Original Set------------------------------------------------------------> | ||
Training | Testing | |
Training | Validation | Testing |
Cross Validation(교차 검증)
- 데스트 데이터셋만을 이요하여 모델의 성능 개선 :
- 데스트 데이터에만 최적화된 모델이 만들어짐
- 최종적으로 모델의 서비스 가능 여부를 확인하는 테스트 데이터의 효과가 사라짐
- => Bad!!
- 여러 세트로 구성된 검증 데이터셋을 통해 성능 개선
- 좀 더 다양한 데이터에 최적화된 모델로 학습됨
- 테스트 데이터셋을 이용하여 모델의 최종 서비스 가능 여부 확인 가능
K Fold Cross Validation (K겹 교차 검증)
- 가장 보편적으로 사용되는 교차검증 방법
- K개의 데이터 Fold를 만들어 학습과 검증 평가를 반복 수행
- 데이터 Fold들의 평가 지표를 평균낸 값이 K Fold 평가 지표
- 사이킷런에서 제공되는 API
- KFold
- StratifiedKFold
KFold API
- K겹 교차 검증을 쉽게 적용할 수 있는 API
- Argument
- n_splits : 생성하고자 하는 데이터 Fold의 개수
- shuffle : 데이터 Fold 분리 전 미리 섞을지 여부
- random_state : 실행 시 마다 동일한 난수를 생성하기 위한 값
- ※ shuffle & random_state는 안해줘도 상관 없음
KFold API를 이용한 Cross Validation
- Iris 데이터셋 로드 및 KFold 객체 생성
from sklearn.model_selection import KFold
from sklearn.datasets import load_iris
iris = load_iris()
features = iris.data
label = iris.target
kfold = KFold(n_splits=5)
print('Iris Data Set Size: {}'.format(features.shape[0]))
- Decision Tree 객체 생성 및 Fold 별 지표 값 저장을 위한 리스트 생성
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
dt_clf = DecisionTreeClassifier(random_state=156)
cv_accuracy = []
- KFold 객체의 split() 함수를 이용해 분할된 Fold 별 인덱스 생성
- 생성된 인덱스를 이용해 데이터셋 분할
- 분할된 Fold를 이용하여 모델 학습 및 성능 측정
- Fold별 정확도 지표 측정 및 cv_accuracy 리스트에 추가
for train_index, test_index in kfold.split(features):
x_train, x_test = features[train_index], features[test_index]
y_train, y_test = label[train_index], label[test_index]
dt_clf.fit(x_train,y_train)
pred = dt_clf.predict(x_test)
fold_index += 1
accuracy = np.round(accuracy_score(y_test, pred), 4)
train_size = x_train.shape[0]
test_size = x_test.shape[0]
print('\n#{0} fold accuracy : {1}, train size : {2}, val size : {3}'.
format(fold_index,accuracy, train_size, test_size))
print('#{0} val index : {1}'.format(fold_index,test_index))
cv_accuracy.append(accuracy)
- KFold 평가 지표 출력
- cv_accuracy 리스트에 저장된 Fold 별 정확도 값을 이용해 평균 정확도 계산
- 계산된 KFold 평가지표(평균 정확도) 출력
print('\n## avg val accuracy:', np.mean(cv_accuracy))
Stratified K Fold API
- Stratified K Fold
- Imbalanced(불균형) 분포를 가진 데이터셋을 위한 방식
- 랜덤 샘플링을 하는 KFold의 경우 Imbalanced 데이터셋의 비율을 반영하지 못함
- Stratified K Fold의 경우 데이터셋의 비율을 반영하여 샘플링 수행
- KFold API를 이용하여 Fold 생성 시 데이터의 분포 확인
# Iris 데이터셋 로드하여 DataFrame 객체 생성
from sklearn.datasets import load_iris
import pandas as pd
iris = load_iris()
df_iris = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df_iris['label'] = iris.target
df_iris['label'].value_counts() # 'label' 카테고리별 개수 체크
# KFold import하기
from sklearn.model_selection import KFold
# n_splits 인자를 3으로 지정하여 KFold 객체 생성
kfold = KFold(n_splits=3)
fold_index = 0
for train_index, test_index in kfold.split(df_iris):
fold_index += 1
# KFold API로 생성한 인덱스로 데이터셋 분할
label_train = df_iris['label'].iloc[train_index]
label_test = df_iris['label'].iloc[test_index]
# DataFrame 객체의 value_counts() 메서드를 이용해 데이터 분포 확인
print('## Cross validation: {}'.format(fold_index))
print('Train label distribution:')
print(label_train.value_counts(),end='\n\n')
print('Val label distribution:')
print(label_test.value_counts(),end='\n\n')
- KFold의 경우 Fold별로 데이터셋의 분포가 다른 것 확인 가능
- Stratified K Fold API
- 데이터셋의 비율을 반영해 K겹 교차 검증을 적용할 수 있는 API
- Argument
- n_splits : 생성하고자 하는 데이터 Fold의 개수
- shuffle : 데이터 Fold 분리 전 미리 섞을지 여부
- random_state : 실행 시 마다 동일한 난수를 생성하기 위한 값
- Stratified K Fold API를 이용하여 데이터의 분포 확인
from sklearn.model_selection import StratifiedKFold
# n_splits 인자를 3으로 지정하여 StratifiedKFold 객체 생성
skf = StratifiedKFold(n_splits=3)
fold_index = 0
# StratifiedKFold 객체의 split() 메소드에 분포 확인을 위한 label 데이터셋을 인자로 전달
for train_index, test_index in skf.split(df_iris,df_iris['label']):
fold_index += 1
# StratifiedKFold API로 생성한 인덱스로 데이터셋 분할
label_train = df_iris['label'].iloc[train_index]
label_test = df_iris['label'].iloc[test_index]
# DataFrame 객체의 value_counts() 메서드를 이용해 데이터 분포 확인
print('## Cross validation: {}'.format(fold_index))
print('Train label distribution:')
print(label_train.value_counts(),end='\n\n')
print('Val label distribution:')
print(label_test.value_counts(),end='\n\n')
- Stratified K Fold API 사용시 Fold별로 데이터셋의 분포가 동일한 것 확인 가능
- StratifiedKFold API를 이용한 Cross Validation
# Iris 데이터셋 load
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
import numpy as np
iris = load_iris()
features = iris.data
label = iris.target
# DecisionTreeClassifier 모델 객체 생성
dt_clf = DecisionTreeClassifier(random_state=156)
skfold = StratifiedKFold(n_splits=3)
# Fold별 지표 값 저장을 위한 lst_accuracy 리스트 생성
lst_accuracy = []
fold_index = 0
for train_index, test_index in skf.split(df_iris,df_iris['label']):
# StratifiedKFold API로 생성한 인덱스로 데이터셋 분할
x_train, x_test = features[train_index], features[test_index]
y_train, y_test = label[train_index], label[test_index]
# 분할된 데이터 Fold로 학습 및 예측 수행
dt_clf.fit(x_train,y_train)
pred = dt_clf.predict(x_test)
fold_index += 1
accuracy = np.round(accuracy_score(y_test, pred), 4)
train_size = x_train.shape[0]
test_size = x_test.shape[0]
print('\n#{0} Cross val accuracy : {1}, train size : {2}, val size : {3}'.
format(fold_index,accuracy, train_size, test_size))
print('#{0} Val index : {1}'.format(fold_index,test_index))
lst_accuracy.append(accuracy)
# lst_accuracy 리스트에 저장된 Fold별 정확도 값을 이용해 평균 정확도 계산
# 계산된 KFold 평가지표(평균 정확도) 출력
print('\n## fold val accuracy:', np.round(lst_accuracy,4))
print('## avg val accuracy:',np.mean(lst_accuracy))
'교육 > AI+X 융합 교육' 카테고리의 다른 글
Image Segmentation (0) | 2021.08.24 |
---|---|
[Pytorch] 변형(Transform) (0) | 2021.08.20 |
[Pytorch] Dataset과 Dataloader (0) | 2021.08.20 |
[Pytorch] torchvision (0) | 2021.08.19 |
[210809]싸이킷런을 활용한 간단한 머신러닝 모델 구현(Iris 데이터셋 이용) (0) | 2021.08.12 |