Model Selection 모듈¶
학습/테스트 데이터 세트 분리 - train_test_split()¶
parameter
- test_size
- shuffle: 데이터 분리 전에 미리 섞을지 결정, 디폴트는 True
- random_state
train_test_split의 반환값은 튜플 형태
In [1]:
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import pandas as pd
In [4]:
dt_clf = DecisionTreeClassifier()
iris_data = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris_data.data, iris_data.target, test_size=0.3, random_state=121)
In [7]:
dt_clf.fit(X_train, y_train)
pred = dt_clf.predict(X_test)
pred
Out[7]:
array([1, 2, 1, 0, 0, 1, 1, 1, 1, 2, 2, 1, 1, 0, 0, 2, 1, 0, 2, 0, 2, 2,
1, 1, 1, 1, 0, 0, 2, 2, 1, 2, 0, 0, 1, 2, 0, 0, 0, 2, 2, 2, 2, 0,
1])
In [8]:
print('예측 정확도: {0:.4f}'.format(accuracy_score(y_test, pred)))
예측 정확도: 0.9556
교차 검증¶
- 과적합: 모델이 학습데이터에만 과도하게 최적화되어, 실제 예측을 다른 데이터로 수행할 경우에 성능이 떨어지는 것
- 교차검증은 데이터 편중을 막기 위해 별도의 여러 세트로 구성된 학습데이터 세트와 검증데이터 세트에서 학습과 평가를 수행하는 것
- 대부분 ML모델 성능평가는 교차 검증기반으로 1차 평가를 함
K 폴드 교차 검증¶
- 가장 보편적, K개의 데이터 폴드 세트 만들어서 K번만큼 각 폴드 세트에 학습과 검증 평가를 반복적으로 수행, K개의 평가를 평균한 결과를 가지고 예측 성능 평가
- 학습데이터셋과 검증데이터셋을 점진적으로 변경하면서 K번째까지 수행
- KFold, StratifiedKFold 클래스 제공
In [9]:
# K = 5, 5폴드 교차 검증
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold
import numpy as np
iris = load_iris()
features = iris.data
label = iris.target
dt_clf = DecisionTreeClassifier(random_state=156)
#5개의 폴드 세트로 분리하는 KFold와 폴드 세트별 정확도를 담을 리스트 생성
kfold = KFold(n_splits=5)
cv_accuracy = []
print('붓꽃 데이터 세트 크기:', features.shape[0])
붓꽃 데이터 세트 크기: 150
- 전체 150개 중에서 학습용데이터셋은 120개, 검증은 30개로 분할됨
In [14]:
n_iter = 0
# KFold의 split()을 호출하면 폴드별 학습용, 검증용 테스트의 row index를 array로 반환
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)
n_iter = 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} 교차 검증 정확도: {1}, 학습 데이터 크기 {2}, 검증 데이터 크기: {3}'.format(n_iter, accuracy, train_size, test_size))
print('#{0} 검증 세트 인덱스: {1}'.format(n_iter, test_index))
cv_accuracy.append(accuracy)
#개별 iteration별 정확도를 합하여 평균 정확도 계산
print('\n## 평균 검증 정확도:', np.mean(cv_accuracy))
1 교차 검증 정확도: 1.0, 학습 데이터 크기 120, 검증 데이터 크기: 30
#1 검증 세트 인덱스: [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
24 25 26 27 28 29]
1 교차 검증 정확도: 0.9667, 학습 데이터 크기 120, 검증 데이터 크기: 30
#1 검증 세트 인덱스: [30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
54 55 56 57 58 59]
1 교차 검증 정확도: 0.8667, 학습 데이터 크기 120, 검증 데이터 크기: 30
#1 검증 세트 인덱스: [60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
84 85 86 87 88 89]
1 교차 검증 정확도: 0.9333, 학습 데이터 크기 120, 검증 데이터 크기: 30
#1 검증 세트 인덱스: [ 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
108 109 110 111 112 113 114 115 116 117 118 119]
1 교차 검증 정확도: 0.7333, 학습 데이터 크기 120, 검증 데이터 크기: 30
#1 검증 세트 인덱스: [120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
138 139 140 141 142 143 144 145 146 147 148 149]
## 평균 검증 정확도: 0.9
Stratified K 폴드¶
- 불균형한 분포도를 가진 레이블 데이터 집합을 위한 K폴드 방식
- 불균형한 분포도: 특정 레이블 값이 특이하게 많거나, 적어서 값의 분포가 치우치는 경우
ex) 대출 사기 데이터 예측: 대출 사기 레이블이 1인 레코드는 건수는 적지만 알고리즘이 대출 사기를 예측하기 위한 중요한 feature값을 가지고 있으므로 매우 중요함, 원본 데이터와 유사한 대출 사기 레이블 값의 분포를 학습/테스트셋에도 유지하는게 중요
In [18]:
import pandas as pd
iris = load_iris()
iris_df = pd.DataFrame(iris.data, columns=iris.feature_names)
iris_df['label']=iris.target
iris_df['label'].value_counts()
Out[18]:
0 50
1 50
2 50
Name: label, dtype: int64
In [20]:
#이슈가 발생하는 현상을 도출하기 위해 3개의 폴드 세트를 생성
kfold = KFold(n_splits=3)
n_iter = 0
for train_index, test_indec in kfold.split(iris_df):
n_iter += 1
label_train = iris_df['label'].iloc[train_index]
label_test = iris_df['label'].iloc[test_index]
print('## 교차 검증: {0}'.format(n_iter))
print('학습 레이블 데이터 분포:\n', label_train.value_counts())
print('검증 레이블 데이터 분포:\n', label_test.value_counts())
## 교차 검증: 1
학습 레이블 데이터 분포:
1 50
2 50
Name: label, dtype: int64
검증 레이블 데이터 분포:
2 30
Name: label, dtype: int64
## 교차 검증: 2
학습 레이블 데이터 분포:
0 50
2 50
Name: label, dtype: int64
검증 레이블 데이터 분포:
2 30
Name: label, dtype: int64
## 교차 검증: 3
학습 레이블 데이터 분포:
0 50
1 50
Name: label, dtype: int64
검증 레이블 데이터 분포:
2 30
Name: label, dtype: int64
- 첫 번째 교차 검증에서, 학습레이블은 1,2밖에 없으므로 0의 경우는 전혀 학습하지 못함, 검증레이블에는 0밖에 없어서 모델은 0을 절대 예측하지 못함 >> 이렇게 분할하면 정확도는 0이 될 수밖에없음
- StratifiedKFold는 전체 레이블 값의 분포도를 반영하지 못하는 문제를 해결
- split() 메서드에 인자로 feature 데이터셋뿐만 아니라 label데이터셋도 필요
In [23]:
from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=3)
n_iter = 0
for train_index, test_index in skf.split(iris_df, iris_df['label']):
n_iter += 1
label_train = iris_df['label'].iloc[train_index]
label_test = iris_df['label'].iloc[test_index]
print('## 교차 검증: {0}'.format(n_iter))
print('학습 레이블 데이터 분포:\n', label_train.value_counts())
print('검증 레이블 데이터 분포:\n', label_test.value_counts())
## 교차 검증: 1
학습 레이블 데이터 분포:
2 34
0 33
1 33
Name: label, dtype: int64
검증 레이블 데이터 분포:
0 17
1 17
2 16
Name: label, dtype: int64
## 교차 검증: 2
학습 레이블 데이터 분포:
1 34
0 33
2 33
Name: label, dtype: int64
검증 레이블 데이터 분포:
0 17
2 17
1 16
Name: label, dtype: int64
## 교차 검증: 3
학습 레이블 데이터 분포:
0 34
1 33
2 33
Name: label, dtype: int64
검증 레이블 데이터 분포:
1 17
2 17
0 16
Name: label, dtype: int64
In [30]:
dt_clf = DecisionTreeClassifier(random_state=156)
skfold = StratifiedKFold(n_splits=3)
n_iter = 0
cv_accuracy = []
for train_index, test_index in skfold.split(features, label):
#split으로 반환된 인덱스로 학습용, 검증용 데이터 추출
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)
#반복 시마다 정확도 측정
n_iter += 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} 교차 검증 정확도: {1}, 학습 데이터 크기: {2}, 검증 데이터 크기: {3}'.format(n_iter, accuracy, train_size, test_size))
print('#{0} 검증 세트 인덱스: {1}'.format(n_iter, test_index))
cv_accuracy.append(accuracy)
#교차 검증별 정확도 및 평균 정확도 계산
print('\n ## 교차 검증별 정확도:', np.round(cv_accuracy, 4))
print('## 평균 검증 정확도:', np.round(np.mean(cv_accuracy), 4))
#1 교차 검증 정확도: 0.98, 학습 데이터 크기: 100, 검증 데이터 크기: 50
#1 검증 세트 인덱스: [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 50
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 100 101
102 103 104 105 106 107 108 109 110 111 112 113 114 115]
#2 교차 검증 정확도: 0.94, 학습 데이터 크기: 100, 검증 데이터 크기: 50
#2 검증 세트 인덱스: [ 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 67
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 116 117 118
119 120 121 122 123 124 125 126 127 128 129 130 131 132]
#3 교차 검증 정확도: 0.98, 학습 데이터 크기: 100, 검증 데이터 크기: 50
#3 검증 세트 인덱스: [ 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 83 84
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 133 134 135
136 137 138 139 140 141 142 143 144 145 146 147 148 149]
## 교차 검증별 정확도: [0.98 0.94 0.98]
## 평균 검증 정확도: 0.9667
교차 검증을 보다 간편하게 - cross_val_score()¶
- 앞에서 한 1. 폴드 세트 설정 2. for 루프로 반복으로 학습 및 테스트 데이터 인덱스 추출 3. 반복 힉습, 예측 수행, 성능 반환의 과정을 한꺼번에 수행해줌
- cross_val_score(estimator, X, y=None, scoring=None, cv=None, n_jobs=1, verbose=0, fit_params=None, pre_dispatch='2*n_jobs')
- scoring은 예측 성능 평가 지표 알려줌, cv는 교차 검증 폴드 수
In [31]:
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import cross_val_score, cross_validate
from sklearn.datasets import load_iris
iris_data = load_iris()
dt_clf = DecisionTreeClassifier(random_state=156)
data = iris_data.data
label = iris_data.target
#성능 지표는 정확도, 교차 검증 세트는 3개
scores = cross_val_score(dt_clf, data, label, scoring='accuracy', cv=3)
print('교차 검증별 정확도:', np.round(scores, 4))
print('평균 검증 정확도:', np.round(np.mean(scores), 4))
교차 검증별 정확도: [0.98 0.94 0.98]
평균 검증 정확도: 0.9667
- API 내부에서 학습, 예측, 평가까지 시켜주므로 간단하게 교차 검증 수행 가능
- cross_validate()는 여러개의 평가 지표를 반환할 수 있음, 학습데이터에 대한 성능 평가 지표와 수행 시간도 같이 제공
'Data Science > 파이썬 머신러닝 완벽 가이드' 카테고리의 다른 글
[sklearn] (8) - 데이터 전처리(LabelEncoder, OneHotEncoder, get_dummies, StandardScaler, MinMaxScaler) (0) | 2023.05.02 |
---|---|
[sklearn] (7) - GridSearchCV (0) | 2023.05.02 |
[sklearn] (5) scikit-learn 기반 프레임워크 익히기 (0) | 2023.04.30 |
[sklearn] (4) iris 품종 분류 예측하기 (0) | 2023.04.30 |
[Dacon] 보스턴 집값 예측 (0) | 2023.04.20 |