# 학습/테스트 데이터 분리
from sklearn.model_selection import train_test_split
# 교차 검증
from sklearn.model_selection import KFold
1 학습/테스트 데이터의 이해
1.0.1 학습 데이터로 잘못된 예측 케이스
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
# iris 데이터 로드
iris = load_iris()
# 학습 데이터 세팅
train_data = iris.data
train_label = iris.target
# 디시젼트리 분류기 인스턴스 생성
dt_clf = DecisionTreeClassifier()
# 학습 데이터로 학습
dt_clf.fit(train_data, train_label)
>>> DecisionTreeClassifier()
# 학습 데이터로 예측 수행 : 학습 데이터로 predict(테스트)를 했기 때문에 100%
pred = dt_clf.predict(train_data)
print('예측 정확도:', accuracy_score(train_label,pred))
>>> 예측 정확도: 1.0
1.0.2 테스트 데이터로 predict해야 제대로된 예측
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()
# train_test_split 함수 : 학습, 테스트 데이터 분리
X_train, X_test, y_train, y_test = train_test_split(iris_data.data, iris_data.target,
test_size=0.3, random_state=121)
print(X_train.shape)
>>> (105, 4)
print(X_test.shape)
>>> (45, 4)
# 모델 학습
dt_clf.fit(X_train, y_train)
# 테스트 데이터로 예측
pred = dt_clf.predict(X_test)
print('예측 정확도: {0:.4f}'.format(accuracy_score(y_test,pred)))
>>> 예측 정확도: 0.9556
1.0.3 Pandas 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
print(iris_df.shape)
>>> (150, 5)
iris_df.head()
# 피쳐 정의
ftr_df = iris_df.iloc[:, :-1]
# 타겟 정의
tgt_df = iris_df.iloc[:, -1]
# train_test_split 함수 : 학습/테스트 데이터 나누기
X_train, X_test, y_train, y_test = train_test_split(ftr_df, tgt_df,
test_size=0.3, random_state=121)
# 머신러닝 모델 정의
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
만약 타겟값이 아래와 같다면
target
0 : 5000
1 : 50
2 : 50
고르게 추출하기 위해서 stratify(층화추출)기능을 사용 한다!
train_test_split(ftr_df, tgt_df, test_size=0.3, stratify= , random_state=121)
2 교차 검증
2.0.1 K 폴드
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold
import numpy as np
# 데이터 로드
iris = load_iris()
label = iris.target
features = iris.data
print(features.shape)
features
array([[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.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.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]])
# 모델 정의
dt_clf = DecisionTreeClassifier(random_state=156)
dt_clf
>>> DecisionTreeClassifier(random_state=156)
# 5개의 폴드 세트로 분리하는 KFold 객체와 폴드 세트별 정확도를 담을 리스트 객체 생성.
kfold = KFold(n_splits=5) # n=5
cv_accuracy = [] # 최종적으로는 n번의 교차검증의 평균 정확도 계산
print('붓꽃 데이터 세트 크기:', features.shape[0])
>>> 붓꽃 데이터 세트 크기: 150
# for문이 도는 동안 generator가 kfold된 데이터의 학습, 검증 row 인덱스를 array로 반환
kfold.split(features)
>>> <generator object _BaseKFold.split at 0x00000152CD245120>
n_iter = 0
# KFold객체의 split( ) 호출하면 폴드 별 학습용, 검증용 테스트의 row 인덱스를 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) # 정확도 : 소수점 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]
#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
2.0.2 Stratified K 폴드
KFOLD 교차검증의 문제점 : 불균형한 데이터에는 적용이 안된다.
이를 해결할 방법이 StratifiedKFold : 불균형한 분포도를 가진 레이블 데이터 집합을
균형하게 섞어주고 교차검증을 진행한다.
import pandas as pd
# iris 데이터 로드
iris = load_iris()
iris_df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
# iris 타겟값 확인
iris_df['label'] = iris.target
iris_df['label'].value_counts()
>>>
0 50
1 50
2 50
Name: label, dtype: int64
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('## 교차 검증: {0}'.format(n_iter))
print('학습 레이블 데이터 분포:\n', label_train.value_counts()) # 학습 레이블 분포
print('검증 레이블 데이터 분포:\n', label_test.value_counts(), '\n') # 검증 레이블 분포
## 교차 검증: 1
학습 레이블 데이터 분포:
2 50
1 50
Name: label, dtype: int64
검증 레이블 데이터 분포:
0 50
Name: label, dtype: int64
## 교차 검증: 2
학습 레이블 데이터 분포:
2 50
0 50
Name: label, dtype: int64
검증 레이블 데이터 분포:
1 50
Name: label, dtype: int64
## 교차 검증: 3
학습 레이블 데이터 분포:
1 50
0 50
Name: label, dtype: int64
검증 레이블 데이터 분포:
2 50
Name: label, dtype: int64
-> kfold를 했더니 불균형하게 학습 레이블, 검증 레이블이 들어가 있으므로 검증이 제대로 되지 않는다
이를 해결할 방법이 StratifiedKFold : 불균형한 분포도를 가진 레이블 데이터 집합을
균형하게 섞어주고 교차검증을 진행한다.
from sklearn.model_selection import StratifiedKFold
# StratifiedKFold 클래스의 인스턴스 선언 : skf
skf = StratifiedKFold(n_splits=3)
n_iter=0
# StratifiedKFold 사용시 KFold와 차이점 : 레이블 값을 넣어줘서 레이블에 맞게 균일하게 분포를 맞춰준다.
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(), '\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
-> StratifiedKFold 했더니 균일하게 학습 레이블, 검증 레이블이 들어가 있으므로 검증이 제대로 된다!
2.0.3 최종적으로 StratifiedKFold를 활용한 교차 검증 정확도 확인
from sklearn.model_selection import StratifiedKFold
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
-> 아까보다 좋은 검증 정확도가 나왔다!
2.1 cross_val_score( ) : 교차검증을 보다 간편하게
폴드 세트 추출, 학습 및 예측, 평가 과정들을 한번에 수행!
from sklearn.tree import DecisionTreeClassifier
# cross_val_score
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
# 성능 지표는 정확도(accuracy), 교차 검증 세트는 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
2.1.1 GridSearchCV : 교차 검증 + 하이퍼 파라미터 튜닝
- 하이퍼 파라미터 : 모델의 성능을 최대로 끌어올리는 학습 조건
- 하이퍼 파라미터 튜닝의 중요성 : 학습 조건을 잘 설정해야 최대의 성능을 내는 머신러닝 모델을 얻을 수 있다.
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.metrics import accuracy_score
# iris 데이터를 로드
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()
### hyper-parameter 들을 딕셔너리 형태로 설정
parameters = {'max_depth':[1, 2, 3], 'min_samples_split':[2,3]}
max_depth는 dicision_tree에서 분기의 수를 말한다.
mport pandas as pd
# param_grid의 하이퍼 파라미터들을 3개의 train, test set fold 로 나누어서 테스트 수행 설정.
grid_dtree = GridSearchCV(dtree, param_grid=parameters, cv=3, refit=True, return_train_score=True)
### refit=True 가 default : 가장 좋은 파라미터 설정으로 재 학습 시킴.
# 붓꽃 Train 데이터로 param_grid의 하이퍼 파라미터들을 순차적으로 학습/평가 .
grid_dtree.fit(X_train, y_train)
>>>
GridSearchCV(cv=3, estimator=DecisionTreeClassifier(),
param_grid={'max_depth': [1, 2, 3], 'min_samples_split': [2, 3]},
return_train_score=True)
grid_dtree.cv_results_
{'mean_fit_time': array([0. , 0.00016785, 0. , 0.00037972, 0. ,
0.00033458]),
'std_fit_time': array([0. , 0.00023737, 0. , 0.00053701, 0. ,
0.00047317]),
'mean_score_time': array([0.00058389, 0. , 0.00033387, 0. , 0. ,
0. ]),
'std_score_time': array([0.00042873, 0. , 0.00047216, 0. , 0. ,
0. ]),
'param_max_depth': masked_array(data=[1, 1, 2, 2, 3, 3],
mask=[False, False, False, False, False, False],
fill_value='?',
dtype=object),
'param_min_samples_split': masked_array(data=[2, 3, 2, 3, 2, 3],
mask=[False, False, False, False, False, False],
fill_value='?',
dtype=object),
'params': [{'max_depth': 1, 'min_samples_split': 2},
{'max_depth': 1, 'min_samples_split': 3},
{'max_depth': 2, 'min_samples_split': 2},
{'max_depth': 2, 'min_samples_split': 3},
{'max_depth': 3, 'min_samples_split': 2},
{'max_depth': 3, 'min_samples_split': 3}],
'split0_test_score': array([0.7 , 0.7 , 0.925, 0.925, 0.975, 0.975]),
'split1_test_score': array([0.7, 0.7, 1. , 1. , 1. , 1. ]),
'split2_test_score': array([0.7 , 0.7 , 0.95, 0.95, 0.95, 0.95]),
'mean_test_score': array([0.7 , 0.7 , 0.95833333, 0.95833333, 0.975 ,
0.975 ]),
'std_test_score': array([1.11022302e-16, 1.11022302e-16, 3.11804782e-02, 3.11804782e-02,
2.04124145e-02, 2.04124145e-02]),
'rank_test_score': array([5, 5, 3, 3, 1, 1]),
'split0_train_score': array([0.7 , 0.7 , 0.975 , 0.975 , 0.9875, 0.9875]),
'split1_train_score': array([0.7 , 0.7 , 0.9375, 0.9375, 0.9625, 0.9625]),
'split2_train_score': array([0.7 , 0.7 , 0.9625, 0.9625, 0.9875, 0.9875]),
'mean_train_score': array([0.7 , 0.7 , 0.95833333, 0.95833333, 0.97916667,
0.97916667]),
'std_train_score': array([1.11022302e-16, 1.11022302e-16, 1.55902391e-02, 1.55902391e-02,
1.17851130e-02, 1.17851130e-02])}
# 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']]
-> 가장 좋은 hyper-parameter는 {'max_depth': 3, 'min_samples_split': 2}
# (참고) GridSearchCV 결과 전체 확인
grid_dtree.cv_results_
{'mean_fit_time': array([0.00081412, 0. , 0. , 0.0006992 , 0.00050243,
0.00067306]),
'std_fit_time': array([0.00059235, 0. , 0. , 0.00049572, 0.00040968,
0.00047595]),
'mean_score_time': array([0.00016809, 0. , 0. , 0. , 0. ,
0.00033458]),
'std_score_time': array([0.00023771, 0. , 0. , 0. , 0. ,
0.00047317]),
'param_max_depth': masked_array(data=[1, 1, 2, 2, 3, 3],
mask=[False, False, False, False, False, False],
fill_value='?',
dtype=object),
'param_min_samples_split': masked_array(data=[2, 3, 2, 3, 2, 3],
mask=[False, False, False, False, False, False],
fill_value='?',
dtype=object),
'params': [{'max_depth': 1, 'min_samples_split': 2},
{'max_depth': 1, 'min_samples_split': 3},
{'max_depth': 2, 'min_samples_split': 2},
{'max_depth': 2, 'min_samples_split': 3},
{'max_depth': 3, 'min_samples_split': 2},
{'max_depth': 3, 'min_samples_split': 3}],
'split0_test_score': array([0.7 , 0.7 , 0.925, 0.925, 0.975, 0.975]),
'split1_test_score': array([0.7, 0.7, 1. , 1. , 1. , 1. ]),
'split2_test_score': array([0.7 , 0.7 , 0.95, 0.95, 0.95, 0.95]),
'mean_test_score': array([0.7 , 0.7 , 0.95833333, 0.95833333, 0.975 ,
0.975 ]),
'std_test_score': array([1.11022302e-16, 1.11022302e-16, 3.11804782e-02, 3.11804782e-02,
2.04124145e-02, 2.04124145e-02]),
'rank_test_score': array([5, 5, 3, 3, 1, 1]),
'split0_train_score': array([0.7 , 0.7 , 0.975 , 0.975 , 0.9875, 0.9875]),
'split1_train_score': array([0.7 , 0.7 , 0.9375, 0.9375, 0.9625, 0.9625]),
'split2_train_score': array([0.7 , 0.7 , 0.9625, 0.9625, 0.9875, 0.9875]),
'mean_train_score': array([0.7 , 0.7 , 0.95833333, 0.95833333, 0.97916667,
0.97916667]),
'std_train_score': array([1.11022302e-16, 1.11022302e-16, 1.55902391e-02, 1.55902391e-02,
1.17851130e-02, 1.17851130e-02])}
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
# 테스트 데이터 예측 정확도 확인
accuracy_score(y_test, pred)
>>> 0.9666666666666667
estimator 종류
1. 분류 : DecisionTreeClassifier, RandomForestClassifier, ...
2. 회귀 : LinearRegression, ...
# GridSearchCV의 refit으로 이미 학습이 된 estimator 반환
# 위에서 dtree = DecisionTreeClassifier() 로 estimator를 선언했고, 이를 GridSearchCV에 넣었으므로,
estimator = grid_dtree.best_estimator_
estimator
>>> DecisionTreeClassifier(max_depth=3)
# GridSearchCV의 best_estimator_는 이미 최적 하이퍼 파라미터로 학습이 됨
pred = estimator.predict(X_test)
print('테스트 데이터 세트 정확도: {0:.4f}'.format(accuracy_score(y_test, pred)))
>>> 테스트 데이터 세트 정확도: 0.9667
결론:
GridSearchCV를 사용했더니 교차검증을 통해 최적의 모델 성능을 내는 하이퍼 파라미터 튜닝을 했다.
즉, 정확도가 높은 모델을 얻었다!
'Machine Learning > 머신러닝 완벽가이드 for Python' 카테고리의 다른 글
2.5 데이터_전처리(데이터 인코딩, 피처스케일링과 정규화) (실습) (0) | 2022.10.06 |
---|---|
Ch.2.5 데이터 전처리 (0) | 2022.10.06 |
ch.2.4 sklearn.model_selection (1) | 2022.10.05 |
ch 2.3 사이킷런의 내장 예제 데이터 (실습) (1) | 2022.10.05 |
ch.2.3 사이킷런 프레임워크 (1) | 2022.10.05 |