사이킷런(Sklearn)


사이킷런 version 확인

import sklearn
print(sklearn.__version__)
0.24.2

붓꽃 예측을 위한 사이킷런 필요 모듈 로딩

from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split

데이터 세트를 로딩

import pandas as pd

# 붓꽃 데이터 세트를 로딩
iris = load_iris()

# iris.data는 Iris 데이터 세트에서 피처만으로 된 데이터를 numpy로 가지고 있음
iris_data = iris.data

# iris.target은 붓꽃 데이터 세트에서 레이블(결정 값) 데이터를 numpy로 가지고 있음
iris_label = iris.target

print("iris target 값 : {}".format(iris_label))
print("iris target 명 : {}".format(iris.target_names))

# 붓꽃 데이터 세트를 자세히 보기 위해 DataFrame으로 변환
iris_df = pd.DataFrame(data = iris_data, columns = iris.feature_names)
iris_df["label"] = iris_label
iris_df.head(3)
iris target 값 : [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2]
iris target 명 : ['setosa' 'versicolor' 'virginica']
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) label
0 5.1 3.5 1.4 0.2 0
1 4.9 3.0 1.4 0.2 0
2 4.7 3.2 1.3 0.2 0

학습 데이터와 테스트 데이터 세트로 분리

X_train, X_test, y_train, y_test = train_test_split(iris_data, iris_label, test_size = 0.2, random_state = 11)
  • X를 피쳐, y를 타겟 으로 하는 것이 일반적

학습 데이터 세트로 학습(Train) 수행

# DiecisionTreeClassifier 객체 생성
dt_clf = DecisionTreeClassifier(random_state = 11)

# 학습 수행
dt_clf.fit(X_train, y_train)
DecisionTreeClassifier(random_state=11)

테스트 데이터 세트로 예측 수행

# 학습이 완료된 DecisionTreeClassifier 객체에서 테스트 데이터 세트로 예측 수행.
pred = dt_clf.predict(X_test)
pred
array([2, 2, 1, 1, 2, 0, 1, 0, 0, 1, 1, 1, 1, 2, 2, 0, 2, 1, 2, 2, 1, 0,
       0, 1, 0, 0, 2, 1, 0, 1])

예측 정확도 평가

from sklearn.metrics import accuracy_score
print("예측 정확도 : {0:.4f}".format(accuracy_score(y_test, pred)))
예측 정확도 : 0.9333



포함되어 있는 Data 확인하기


from sklearn.datasets import load_iris

iris_data = load_iris()
print(type(iris_data))
<class 'sklearn.utils.Bunch'>
keys = iris_data.keys()
print("붓꽃 데이터 세트의 키들 : {}".format(keys))
붓꽃 데이터 세트의 키들 : dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename'])

키는 보통 data, target, target_names, feature_names, DESCR 로 구성

  • data는 피처의 데이터 세트
  • target은 분류 시 레이블 값, 회귀 시 결과값
  • target_names은 개별 레이블의 이름
  • feature_names는 피처의 이름
  • DESCR은 데이터 세트에 대한 설명과 각 피처의 설명
print("feature_names의 type : {}".format(type(iris_data.feature_names)))
print(" feature_names의 shape : {}".format(len(iris_data.feature_names)))
print(iris_data.feature_names)

print("-" * 90)

print("target_names의 type : {}".format(type(iris_data.target_names)))
print(" target_names의 shpae : {}".format(len(iris_data.target_names)))
print(iris_data.target_names)

print("-" * 90)

print("data의 type : {}".format(type(iris_data.data)))
print( "data의 shpae : {}".format(iris_data.data.shape))
print(iris_data.data)

print("-" * 90)

print("target의 type : {}".format(type(iris_data.target)))
print(" target의 shape : {}".format(iris_data.target.shape))
print(iris_data.target)

feature_names의 type : <class 'list'>
 feature_names의 shape : 4
['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
------------------------------------------------------------------------------------------
target_names의 type : <class 'numpy.ndarray'>
 target_names의 shpae : 3
['setosa' 'versicolor' 'virginica']
------------------------------------------------------------------------------------------
data의 type : <class 'numpy.ndarray'>
data의 shpae : (150, 4)
[[5.1 3.5 1.4 0.2]
 [4.9 3.  1.4 0.2]
 [4.7 3.2 1.3 0.2]
 [4.6 3.1 1.5 0.2]
 [5.  3.6 1.4 0.2]
 [5.4 3.9 1.7 0.4]
 [4.6 3.4 1.4 0.3]
 [5.  3.4 1.5 0.2]
 [4.4 2.9 1.4 0.2]
 [4.9 3.1 1.5 0.1]
 [5.4 3.7 1.5 0.2]
 [4.8 3.4 1.6 0.2]
 [4.8 3.  1.4 0.1]
 [4.3 3.  1.1 0.1]
 [5.8 4.  1.2 0.2]
 [5.7 4.4 1.5 0.4]
 [5.4 3.9 1.3 0.4]
 [5.1 3.5 1.4 0.3]
 [5.7 3.8 1.7 0.3]
 [5.1 3.8 1.5 0.3]
 [5.4 3.4 1.7 0.2]
 [5.1 3.7 1.5 0.4]
 [4.6 3.6 1.  0.2]
 [5.1 3.3 1.7 0.5]
 [4.8 3.4 1.9 0.2]
 [5.  3.  1.6 0.2]
 [5.  3.4 1.6 0.4]
 [5.2 3.5 1.5 0.2]
 [5.2 3.4 1.4 0.2]
 [4.7 3.2 1.6 0.2]
 [4.8 3.1 1.6 0.2]
 [5.4 3.4 1.5 0.4]
 [5.2 4.1 1.5 0.1]
 [5.5 4.2 1.4 0.2]
 [4.9 3.1 1.5 0.2]
 [5.  3.2 1.2 0.2]
 [5.5 3.5 1.3 0.2]
 [4.9 3.6 1.4 0.1]
 [4.4 3.  1.3 0.2]
 [5.1 3.4 1.5 0.2]
 [5.  3.5 1.3 0.3]
 [4.5 2.3 1.3 0.3]
 [4.4 3.2 1.3 0.2]
 [5.  3.5 1.6 0.6]
 [5.1 3.8 1.9 0.4]
 [4.8 3.  1.4 0.3]
 [5.1 3.8 1.6 0.2]
 [4.6 3.2 1.4 0.2]
 [5.3 3.7 1.5 0.2]
 [5.  3.3 1.4 0.2]
 [7.  3.2 4.7 1.4]
 [6.4 3.2 4.5 1.5]
 [6.9 3.1 4.9 1.5]
 [5.5 2.3 4.  1.3]
 [6.5 2.8 4.6 1.5]
 [5.7 2.8 4.5 1.3]
 [6.3 3.3 4.7 1.6]
 [4.9 2.4 3.3 1. ]
 [6.6 2.9 4.6 1.3]
 [5.2 2.7 3.9 1.4]
 [5.  2.  3.5 1. ]
 [5.9 3.  4.2 1.5]
 [6.  2.2 4.  1. ]
 [6.1 2.9 4.7 1.4]
 [5.6 2.9 3.6 1.3]
 [6.7 3.1 4.4 1.4]
 [5.6 3.  4.5 1.5]
 [5.8 2.7 4.1 1. ]
 [6.2 2.2 4.5 1.5]
 [5.6 2.5 3.9 1.1]
 [5.9 3.2 4.8 1.8]
 [6.1 2.8 4.  1.3]
 [6.3 2.5 4.9 1.5]
 [6.1 2.8 4.7 1.2]
 [6.4 2.9 4.3 1.3]
 [6.6 3.  4.4 1.4]
 [6.8 2.8 4.8 1.4]
 [6.7 3.  5.  1.7]
 [6.  2.9 4.5 1.5]
 [5.7 2.6 3.5 1. ]
 [5.5 2.4 3.8 1.1]
 [5.5 2.4 3.7 1. ]
 [5.8 2.7 3.9 1.2]
 [6.  2.7 5.1 1.6]
 [5.4 3.  4.5 1.5]
 [6.  3.4 4.5 1.6]
 [6.7 3.1 4.7 1.5]
 [6.3 2.3 4.4 1.3]
 [5.6 3.  4.1 1.3]
 [5.5 2.5 4.  1.3]
 [5.5 2.6 4.4 1.2]
 [6.1 3.  4.6 1.4]
 [5.8 2.6 4.  1.2]
 [5.  2.3 3.3 1. ]
 [5.6 2.7 4.2 1.3]
 [5.7 3.  4.2 1.2]
 [5.7 2.9 4.2 1.3]
 [6.2 2.9 4.3 1.3]
 [5.1 2.5 3.  1.1]
 [5.7 2.8 4.1 1.3]
 [6.3 3.3 6.  2.5]
 [5.8 2.7 5.1 1.9]
 [7.1 3.  5.9 2.1]
 [6.3 2.9 5.6 1.8]
 [6.5 3.  5.8 2.2]
 [7.6 3.  6.6 2.1]
 [4.9 2.5 4.5 1.7]
 [7.3 2.9 6.3 1.8]
 [6.7 2.5 5.8 1.8]
 [7.2 3.6 6.1 2.5]
 [6.5 3.2 5.1 2. ]
 [6.4 2.7 5.3 1.9]
 [6.8 3.  5.5 2.1]
 [5.7 2.5 5.  2. ]
 [5.8 2.8 5.1 2.4]
 [6.4 3.2 5.3 2.3]
 [6.5 3.  5.5 1.8]
 [7.7 3.8 6.7 2.2]
 [7.7 2.6 6.9 2.3]
 [6.  2.2 5.  1.5]
 [6.9 3.2 5.7 2.3]
 [5.6 2.8 4.9 2. ]
 [7.7 2.8 6.7 2. ]
 [6.3 2.7 4.9 1.8]
 [6.7 3.3 5.7 2.1]
 [7.2 3.2 6.  1.8]
 [6.2 2.8 4.8 1.8]
 [6.1 3.  4.9 1.8]
 [6.4 2.8 5.6 2.1]
 [7.2 3.  5.8 1.6]
 [7.4 2.8 6.1 1.9]
 [7.9 3.8 6.4 2. ]
 [6.4 2.8 5.6 2.2]
 [6.3 2.8 5.1 1.5]
 [6.1 2.6 5.6 1.4]
 [7.7 3.  6.1 2.3]
 [6.3 3.4 5.6 2.4]
 [6.4 3.1 5.5 1.8]
 [6.  3.  4.8 1.8]
 [6.9 3.1 5.4 2.1]
 [6.7 3.1 5.6 2.4]
 [6.9 3.1 5.1 2.3]
 [5.8 2.7 5.1 1.9]
 [6.8 3.2 5.9 2.3]
 [6.7 3.3 5.7 2.5]
 [6.7 3.  5.2 2.3]
 [6.3 2.5 5.  1.9]
 [6.5 3.  5.2 2. ]
 [6.2 3.4 5.4 2.3]
 [5.9 3.  5.1 1.8]]
------------------------------------------------------------------------------------------
target의 type : <class 'numpy.ndarray'>
 target의 shape : (150,)
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2]

학습/테스트 데이터 셋 분리 - train_test_split()

from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score

iris = load_iris()
dt_clf = DecisionTreeClassifier()
train_data = iris.data
train_label = iris.target

# 학습 수행
dt_clf.fit(train_data, train_label)

# 학습 데이터 셋으로 예측 수행
pred = dt_clf.predict(train_data)
print("예측 정확도 : {}".format(accuracy_score(train_label, pred)))
예측 정확도 : 1.0

train_data로 학습을 수행시켰고, 또한 예측도 수행했으므로 예측 정확도가 1

모의고사 문제로 수능을 본 것과 같은 상황

그렇기 때문에 예측을 수행할 때는 별도의 test_data로 해야한다.

from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split


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)
  • X_train : train용 feature data
  • X_test : test용 feature data
  • y_train : train용 label data
  • y_test : test용 label data
dt_clf.fit(X_train, y_train)
pred = dt_clf.predict(X_test)
print("예측 정확도 : {:.4f}".format(accuracy_score(y_test, pred)))
예측 정확도 : 0.9556

넘파이 ndarray 뿐만 아니라 판다스 DataFrame/Series도 train_test_split()으로 분할 가능

import pandas as pd

iris_df = pd.DataFrame(iris_data.data, columns = iris_data.feature_names)
iris_df["target"] = iris_data.target
iris_df.head()
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target
0 5.1 3.5 1.4 0.2 0
1 4.9 3.0 1.4 0.2 0
2 4.7 3.2 1.3 0.2 0
3 4.6 3.1 1.5 0.2 0
4 5.0 3.6 1.4 0.2 0
ftr_df = iris_df.iloc[:, :-1]
tgt_df = iris_df.iloc[:, -1]

X_train, X_test, y_train, y_test = train_test_split(ftr_df, tgt_df, 
                                                    test_size = 0.3, random_state = 121)
print(type(X_train), type(X_test), type(y_train), type(y_test))
<class 'pandas.core.frame.DataFrame'> <class 'pandas.core.frame.DataFrame'> <class 'pandas.core.series.Series'> <class 'pandas.core.series.Series'>
dt_clf = DecisionTreeClassifier()
dt_clf.fit(X_train, y_train)
pred = dt_clf.predict(X_test)
print("예측 정확도 : {0:.4f}".format(accuracy_score(y_test, pred)))
예측 정확도 : 0.9556

교차 검증

K 폴드

from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold
from sklearn.datasets import load_iris
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("붓꽃 데이터 세트 크기 : {}".format(features.shape[0]))
붓꽃 데이터 세트 크기 : 150
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("{} 교차 검증 정확도 : {}, 학습 데이터 크기 : {}, 검증 데이터 크기 : {}"
         .format(n_iter, accuracy, train_size, test_size))
    print("{} 검증 세트 인덱스 : {}".format(n_iter, test_index))
    
    cv_accuracy.append(accuracy)
    
    print("")
    
# 개별 iteration별 정확도를 합하여 평균 정확도 계산
print("평균 검증 정확도 : {}".format(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

Stratified K 폴드

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()
0    50
1    50
2    50
Name: label, dtype: int64

먼저 KFold로 확인을 해보도록 하자

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("## 교차 검증 : {}".format(n_iter))
    print("")
    print("학습 레이블 데이터 분포 : \n{}".format(label_train.value_counts()))
    print("검증 레이블 데이터 분포 : \n{}".format(label_test.value_counts()))
    print("-" * 30)
## 교차 검증 : 1

학습 레이블 데이터 분포 : 
1    50
2    50
Name: label, dtype: int64
검증 레이블 데이터 분포 : 
0    50
Name: label, dtype: int64
------------------------------
## 교차 검증 : 2

학습 레이블 데이터 분포 : 
0    50
2    50
Name: label, dtype: int64
검증 레이블 데이터 분포 : 
1    50
Name: label, dtype: int64
------------------------------
## 교차 검증 : 3

학습 레이블 데이터 분포 : 
0    50
1    50
Name: label, dtype: int64
검증 레이블 데이터 분포 : 
2    50
Name: label, dtype: int64
------------------------------
  • KFold를 사용하였을 때는 학습 레이블이 몰려있는 상황이다.

  • 이와 같은 상황은 학습이 제대로 이루어지지 못하는 상황이다.

StratifiedKFold로 확인을 해보자

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("## 교차 검증 : {}".format(n_iter))
    print("")
    print("학습 레이블 데이터 분포 : \n{}".format(label_train.value_counts()))
    print("검증 레이블 데이터 분포 : \n{}".format(label_test.value_counts()))
    print("-" * 30)
## 교차 검증 : 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
------------------------------
  • 레이블들이 골고루 분포되어 있기에 학습이 제대로 이루어진 상황
dt_clf = DecisionTreeClassifier(random_state=156)

skfold = StratifiedKFold(n_splits=3)
n_iter=0
cv_accuracy=[]

# StratifiedKFold의 split( ) 호출시 반드시 레이블 데이터 셋도 추가 입력 필요  
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.mean(cv_accuracy)) 
#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.9666666666666667

KFold 클래스를 이용한 교차 검증 방법

    1. 폴드 세트 설정
    1. For 루프에서 반복적으로 학습/검증 데이터 추출 및 학습, 예측 수행
    1. 폴드 세트별로 예측 성능을 평균하여 최종 성능 평가

이 과정을 cross_val_score()를 통해 한번에 수행

GridSearchCV를 통해 교차 검증과 최적 하이퍼 파라미터 튜닝을 한번에 가능


cross_val_score()

from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import cross_val_score, cross_validate
from sklearn.datasets import load_iris
import numpy as np

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("교차 검증별 정확도 : {}".format(np.round(scores, 4)))
print("평균 검증 정확도 : {}".format(np.mean(scores), 4))
교차 검증별 정확도 : [0.98 0.94 0.98]
평균 검증 정확도 : 0.9666666666666667

GridSearchCV

from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score

# 데이터를 로닝하고 학습데이터와 테스트 데이터 분리
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris_data.data, iris_data.target,
                                                   test_size = 0.2, random_state = 121)

dtree = DecisionTreeClassifier()

# parameter들을 dictionary 형태로 설정
parameters = {"max_depth" : [1, 2, 3], "min_samples_split" : [2, 3]}
import pandas as pd

# param_grid의 하이퍼 파라미터들을 3개의 train, test set fold 로 나누어서 테스트 수행 설정.  
### refit=True 가 default 임. True이면 가장 좋은 파라미터 설정으로 재 학습 시킴.  
grid_dtree = GridSearchCV(dtree, param_grid=parameters, cv=3, refit=True, return_train_score=True)

# 붓꽃 Train 데이터로 param_grid의 하이퍼 파라미터들을 순차적으로 학습/평가 .
grid_dtree.fit(X_train, y_train)

# GridSearchCV 결과는 cv_results_ 라는 딕셔너리로 저장됨. 이를 DataFrame으로 변환
scores_df = pd.DataFrame(grid_dtree.cv_results_)
scores_df[['params', 'mean_test_score', 'rank_test_score', 
           'split0_test_score', 'split1_test_score', 'split2_test_score']]
params mean_test_score rank_test_score split0_test_score split1_test_score split2_test_score
0 {'max_depth': 1, 'min_samples_split': 2} 0.700000 5 0.700 0.7 0.70
1 {'max_depth': 1, 'min_samples_split': 3} 0.700000 5 0.700 0.7 0.70
2 {'max_depth': 2, 'min_samples_split': 2} 0.958333 3 0.925 1.0 0.95
3 {'max_depth': 2, 'min_samples_split': 3} 0.958333 3 0.925 1.0 0.95
4 {'max_depth': 3, 'min_samples_split': 2} 0.975000 1 0.975 1.0 0.95
5 {'max_depth': 3, 'min_samples_split': 3} 0.975000 1 0.975 1.0 0.95
print('GridSearchCV 최적 파라미터:', grid_dtree.best_params_)
print('GridSearchCV 최고 정확도: {0:.4f}'.format(grid_dtree.best_score_))

# refit=True로 설정된 GridSearchCV 객체가 fit()을 수행 시 학습이 완료된 Estimator를 내포하고 있으므로 predict()를 통해 예측도 가능. 
pred = grid_dtree.predict(X_test)
print('테스트 데이터 세트 정확도: {0:.4f}'.format(accuracy_score(y_test,pred)))
GridSearchCV 최적 파라미터: {'max_depth': 3, 'min_samples_split': 2}
GridSearchCV 최고 정확도: 0.9750
테스트 데이터 세트 정확도: 0.9667
# GridSearchCV의 refit으로 이미 학습이 된 estimator 반환
estimator = grid_dtree.best_estimator_

# GridSearchCV의 best_estimator_는 이미 최적 하이퍼 파라미터로 학습이 됨
pred = estimator.predict(X_test)
print('테스트 데이터 세트 정확도: {0:.4f}'.format(accuracy_score(y_test,pred)))
테스트 데이터 세트 정확도: 0.9667

데이터 인코딩

레이블 인코딩(Label encoding)

from sklearn.preprocessing import LabelEncoder

items = ["TV", "냉장고", "전자렌지", "컴퓨터", "선풍기", "선풍기", "믹서", "믹서"]

# LabelEncoder를 객체로 생성한 후, fit()과 transform()으로 label 인코딩 수행.
encoder = LabelEncoder()
encoder.fit(items)
labels = encoder.transform(items)
print("인코딩 변환값 : {}".format(labels))
인코딩 변환값 : [0 1 4 5 3 3 2 2]
print("인코딩 클래스 : {}".format(encoder.classes_))
인코딩 클래스 : ['TV' '냉장고' '믹서' '선풍기' '전자렌지' '컴퓨터']
print("디코딩 원본값 : {}".format(encoder.inverse_transform([4, 5, 2, 0, 1, 1, 3, 3])))
디코딩 원본값 : ['전자렌지' '컴퓨터' '믹서' 'TV' '냉장고' '냉장고' '선풍기' '선풍기']

원-핫 인코딩(One-Hot encoding)

from sklearn.preprocessing import OneHotEncoder
import numpy as np

items = ["TV", "냉장고", "전자렌지", "컴퓨터", "선풍기", "선풍기", "믹서", "믹서"]

# 먼저 숫자값으로 변환을 위해 label encoding
encoder = LabelEncoder()
encoder.fit(items)
labels = encoder.transform(items)

# 2차원 데이터로 변환
labels = labels.reshape(-1, 1)

# 원-핫 인코딩 적용|
oh_encoder = OneHotEncoder()
oh_encoder.fit(labels)
oh_labels = oh_encoder.transform(labels)

print("원-핫 인코딩 데이터 : \n{}".format(oh_labels.toarray()))
print("")
print("원-핫 인코딩 데이터 차원 : \n{}".format(oh_labels.shape))
원-핫 인코딩 데이터 : 
[[1. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 0. 1.]
 [0. 0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0. 0.]
 [0. 0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0.]]

원-핫 인코딩 데이터 차원 : 
(8, 6)

get_dummies()

  • 원-핫 인코딩을 좀 더 편리하게 적용
import pandas as pd

df = pd.DataFrame({ "items" : ["TV", "냉장고", "전자렌지", "컴퓨터", "선풍기", "선풍기", "믹서", "믹서"] })
df
items
0 TV
1 냉장고
2 전자렌지
3 컴퓨터
4 선풍기
5 선풍기
6 믹서
7 믹서
pd.get_dummies(df)
items_TV items_냉장고 items_믹서 items_선풍기 items_전자렌지 items_컴퓨터
0 1 0 0 0 0 0
1 0 1 0 0 0 0
2 0 0 0 0 1 0
3 0 0 0 0 0 1
4 0 0 0 1 0 0
5 0 0 0 1 0 0
6 0 0 1 0 0 0
7 0 0 1 0 0 0

피처 스케일링

  • StandardScaler : 평균이 0이고, 분산이 1인 정규 분포 형태로 변환

  • MinMaxScaler : 데이터 값을 0과 1사이의 범위 값으로 변환

StandardScaler

from sklearn.datasets import load_iris
import pandas as pd
# 붓꽃 데이터 셋을 로딩하여 DataFrame으로 변환해보자

iris = load_iris()
iris_data = iris.data
iris_df = pd.DataFrame(data = iris_data, columns = iris.feature_names)

iris_df

print("feature들의 평균 값 : \n\n{}".format(iris_df.mean(axis = 0)))
print("-" * 30)
print("feature들의 분산 값 : \n\n{}".format(iris_df.var(axis = 0)))
feature들의 평균 값 : 

sepal length (cm)    5.843333
sepal width (cm)     3.057333
petal length (cm)    3.758000
petal width (cm)     1.199333
dtype: float64
------------------------------
feature들의 분산 값 : 

sepal length (cm)    0.685694
sepal width (cm)     0.189979
petal length (cm)    3.116278
petal width (cm)     0.581006
dtype: float64
from sklearn.preprocessing import StandardScaler

# StandScaler 객체 생성
scaler = StandardScaler()

# StandardScaler로 데이터 셋 변환, fit()과 transform()호출
scaler.fit(iris_df)
iris_scaled = scaler.transform(iris_df)

# transform시 scale 변환된 데이터 셋이 numpy ndarray로 반환되므로 DataFrame으로 변환
iris_df_scaled = pd.DataFrame(data = iris_scaled, columns = iris.feature_names)
print("feature들의 평균 값 : \n\n{}".format(iris_df_scaled.mean(axis=0)))
print("-" * 30)
print("feature들의 분산 값 : \n\n{}".format(iris_df_scaled.var(axis=0)))

feature들의 평균 값 : 

sepal length (cm)   -1.690315e-15
sepal width (cm)    -1.842970e-15
petal length (cm)   -1.698641e-15
petal width (cm)    -1.409243e-15
dtype: float64
------------------------------
feature들의 분산 값 : 

sepal length (cm)    1.006711
sepal width (cm)     1.006711
petal length (cm)    1.006711
petal width (cm)     1.006711
dtype: float64

StandardScaler로 데이터 셋의 평균을 0, 분산을 1로 만들었다.


MinMaxScaler

from sklearn.preprocessing import MinMaxScaler

# MinMaxScaler 객체 생성
scaler = MinMaxScaler()
scaler.fit(iris_df)
iris_scaled = scaler.transform(iris_df)

# transform시 scale변환된 데이터 셋이 numpy ndarray이므로 DataFrame으로 변환
iris_df_scaled = pd.DataFrame(data = iris_scaled, columns = iris.feature_names)
print("feature들의 최소값 : \n\n{}".format(iris_df_scaled.min(axis=0)))
print("-" * 30)
print("feature들의 최대값 : \n\n{}".format(iris_df_scaled.max(axis=0)))
feature들의 최소값 : 

sepal length (cm)    0.0
sepal width (cm)     0.0
petal length (cm)    0.0
petal width (cm)     0.0
dtype: float64
------------------------------
feature들의 최대값 : 

sepal length (cm)    1.0
sepal width (cm)     1.0
petal length (cm)    1.0
petal width (cm)     1.0
dtype: float64

MinMaxScaler를 통해 feature의 최소가 0, 최대가 1이 되는 것을 확인