머신러닝

붓꽃 데이터 사이킷 런 학습-교차검증

J.H_DA 2022. 4. 11. 14:25

K- 폴드 교차 검증 

불균형한 분포도를 가진 레이블 데이터 집합을 위한 방법으로 학습데이터와 검증 데이터 세트가 가지는 레이블 분포도가 유사하도록 검증 데이터를 추출 한다.

 

 

sklearn.model_selection.KFold

  • class sklearn.model_selection.KFold(n_splits=5, *, shuffle=False, random_state=None)
In [3]:
from sklearn.datasets import load_iris
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)

kfold = KFold(n_splits=5) #random_state = 0 적어도 된다.
cv_accuracy=[]
print('붓꽃 데이터 세트 크기:', features.shape[0])
붓꽃 데이터 세트 크기: 150
In [24]:
n_iter = 0

# KFold 객체의 split() 호출하면 폴드 별 학습용, 검증용 테스트의 로우 인덱스를 array로 반환
for train_index, test_index  in kfold.split(features):

      #kfold.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(f'#{n_iter} 교차 검증 정확도 {accuracy}, 학습데이터 크기 {train_size}, 검증 크기{test_size}')
      # print('\n#{0} 교차 검증 정확도 : {1}, 학습 데이터 크기: {2}, 검증 데이터 크기: {3}'.format(n_iter, accuracy, train_size, test_size))
      print(f'#{n_iter} , 검증세트 인덱스{test_index}')
      cv_accuracy.append(accuracy)
      
# 개별 iteration별 정확도를 합하여 평균 정확도 계산
print(f'\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]
#2 교차 검증 정확도 0.9667, 학습데이터 크기 120, 검증 크기30
#2 , 검증세트 인덱스[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]
#3 교차 검증 정확도 0.8667, 학습데이터 크기 120, 검증 크기30
#3 , 검증세트 인덱스[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]
#4 교차 검증 정확도 0.9333, 학습데이터 크기 120, 검증 크기30
#4 , 검증세트 인덱스[ 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]
#5 교차 검증 정확도 0.7333, 학습데이터 크기 120, 검증 크기30
#5 , 검증세트 인덱스[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
In [20]:
## 두개의 알고리즘을 사용하여 k-fold 이용
from sklean.linear_model import LogisticRegression
cl_arr = ['DecisionTreeClassfier', 'LogisticRegression']
for i in cl_arr:
print(f'{i}()'')
    for train_index, test_index  in kfold.split(features):

      #kfold.split()으로 반환된 인덱스를 이용하여 학습용, 검증용 테스트 데이터 추출
      X_train, X_test = features[train_index], features[test_index]
      y_train, y_test = label[train_index], label[test_index]
      clf=eval(i)
      # 학습 및 예측
      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(f'#{n_iter} 교차 검증 정확도 {accuracy}, 학습데이터 크기 {train_size}, 검증 크기{test_size}')
      # print('\n#{0} 교차 검증 정확도 : {1}, 학습 데이터 크기: {2}, 검증 데이터 크기: {3}'.format(n_iter, accuracy, train_size, test_size))
      print(f'#{n_iter} , 검증세트 인덱스{test_index}')
      cv_accuracy.append(accuracy)
  File "C:\Users\dooryman\AppData\Local\Temp/ipykernel_14616/1001506809.py", line 5
    print(f'{i}()'')
    ^
IndentationError: expected an indented block

sklearn.model_selection.StratifiedKFold

  • class sklearn.model_selection.StratifiedKFold(n_splits=5, *, shuffle=False, random_state=None)
In [22]:
from sklearn.datasets import load_iris
import pandas as pd

iris = load_iris()

iris_df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
iris_df['label']=iris.target
iris_df['label'].value_counts()
Out[22]:
0    50
1    50
2    50
Name: label, dtype: int64
In [49]:
kfold = KFold(n_splits=3)
# kfold.split(X)는 폴드 세트를 3번 반복할 때마다 달라지는 학습/테스트 용 데이터 로우 인덱스 번호 반환.
n_iter = 0

for train_index, test_index  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(f'#{n_iter} 교차 검증  {0}')
           print('학습 레이블 데이터 분포:\n', label_train.value_counts())
           print('검증 레이블 데이터 분포:\n', label_test.value_counts())
#1 교차 검증  0
학습 레이블 데이터 분포:
 1    50
2    50
Name: label, dtype: int64
검증 레이블 데이터 분포:
 0    50
Name: label, dtype: int64
#2 교차 검증  0
학습 레이블 데이터 분포:
 0    50
2    50
Name: label, dtype: int64
검증 레이블 데이터 분포:
 1    50
Name: label, dtype: int64
#3 교차 검증  0
학습 레이블 데이터 분포:
 0    50
1    50
Name: label, dtype: int64
검증 레이블 데이터 분포:
 2    50
Name: label, dtype: int64
In [50]:
from sklearn.model_selection import StratifiedKFold
iris_df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
iris_df['label'] = iris.target
iris_df['label'].value_counts()
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())
    print("\n")
## 교차 검증 : 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


sklearn.model_selection.cross_val_score

  • sklearn.model_selection.cross_val_score(estimator, X, y=None, , groups=None, scoring=None, cv=None, n_jobs=None, verbose=0, fit_params=None, pre_dispatch='2n_jobs', error_score=nan)
In [51]:
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris

iris_data = load_iris()
dt_clf = DecisionTreeClassifier(random_state=42)

data = iris_data.data
label = iris_data.target

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.96]
평균 검증 정확도 : 0.96
In [ ]:
 
728x90