from IPython.core.display import display, HTML
display(HTML("<style>.container { width:1200px !important; }</style>"))
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_data = iris.data
# iris.target 붓꽃 데이터 세트에서 레이블(결정값) 데이터를 넘파이로 가지고 있다
iris_label = iris.target
print('iris target 값 : ', iris_label)
print('iris target 명 : ', iris.target_names)
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']
# 데이터 프레임으로 생성
iris_df = pd.DataFrame(data=iris_data, columns=iris.feature_names)
iris_df['label'] = iris.target
iris_df.head(3)
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 |
# train 데이터와 test 데이터로 분리
X_train, X_test, y_train, y_test = \
train_test_split(
iris_data # 데이터 셋
, iris_label # 레이블 데이터 셋
, test_size=0.2 # 테스트 데이터 20% 학습데이터 80%
, random_state=11 # 같은 학습/테스트 데이터를 생성하기 위한 난수값
)
# 머신러닝 알고리즘 중 하나인 의사결정 트리를 이용해 학습과 예측
# 의사결정 트리 DecisionTreeClassifier 객체 생성
df_clf = DecisionTreeClassifier(random_state=11 # 같은 학습/테스트 데이터를 생성하기 위한 난수값
)
# 모델생성 수행 : fit()
df_clf.fit(X_train, y_train)
# 학습된 객체를 통해 예측 : predict()
pred = df_clf.predict(X_test)
# 모델 성능 평가
from sklearn.metrics import accuracy_score
# 정확도 측정 : accuracy_score()
print('정확도: {0:.4f}'.format(accuracy_score(y_test,pred)))
정확도: 0.9333
KFold()¶
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)
print('데이터 세트 크기 : ', features.shape[0])
데이터 세트 크기 : (150, 4)
데이터 세트 크기 : 150
n_iter = 0 # k개 분리 후 for문 반복을 위해 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]
# 학습 및 예측
# 모델생성 수행 : fit()
dt_clf.fit(X_train, y_train)
# 학습된 객체를 통해 예측 : predict()
pred = dt_clf.predict(X_test)
n_iter += 1 # 학습과 예측 한 번 돌아가면 세트 추가 > 1세트 > 2세트 > ...> 5세트
# 정확도 측정
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.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
StratifiedKFold¶
- 원본 레이블 데이터의 결정값과 동일한 분배로 학습/검증 데이터를 나눈다
- KFold() 와 차이 : for train_index, test_index in kfold.split(features):
- StratifiedKFold() : for train_index, test_index in skf.split(features,label ):
# 원본 데이터의 레이블값의 분포 확인
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()
2 50
1 50
0 50
Name: label, dtype: int64
from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=5)
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 40
1 40
0 40
Name: label, dtype: int64
검증 레이블 분포:
2 10
1 10
0 10
Name: label, dtype: int64
## 교차검증 : 2
학습 레이블 분포:
2 40
1 40
0 40
Name: label, dtype: int64
검증 레이블 분포:
2 10
1 10
0 10
Name: label, dtype: int64
## 교차검증 : 3
학습 레이블 분포:
2 40
1 40
0 40
Name: label, dtype: int64
검증 레이블 분포:
2 10
1 10
0 10
Name: label, dtype: int64
## 교차검증 : 4
학습 레이블 분포:
2 40
1 40
0 40
Name: label, dtype: int64
검증 레이블 분포:
2 10
1 10
0 10
Name: label, dtype: int64
## 교차검증 : 5
학습 레이블 분포:
2 40
1 40
0 40
Name: label, dtype: int64
검증 레이블 분포:
2 10
1 10
0 10
Name: label, dtype: int64
# StratifiedKFold 검증으로 모델 생성후 다시 예측
# 학습 모델 객체 생성
dt_clf = DecisionTreeClassifier(random_state=156)
skfold = StratifiedKFold(n_splits=5)
n_iter=0
cv_accuracy=[]
# StratifiedKFold split()를 호출하면
# 폴드 별 학습용, 검증용 데이터 와 레이블 데이터의 로우 인덱스를 array로 반환
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('\n## 평균 검증 정확도 : ', np.mean(cv_accuracy))
#1 교차 검증 정확도 : 0.9667, 학습 데이터 크기 : 120, 검증 데이터 크기 : 30
#1 검증 세트 인덱스 [ 0 1 2 3 4 5 6 7 8 9 50 51 52 53 54 55 56 57
58 59 100 101 102 103 104 105 106 107 108 109]
#2 교차 검증 정확도 : 0.9667, 학습 데이터 크기 : 120, 검증 데이터 크기 : 30
#2 검증 세트 인덱스 [ 10 11 12 13 14 15 16 17 18 19 60 61 62 63 64 65 66 67
68 69 110 111 112 113 114 115 116 117 118 119]
#3 교차 검증 정확도 : 0.9, 학습 데이터 크기 : 120, 검증 데이터 크기 : 30
#3 검증 세트 인덱스 [ 20 21 22 23 24 25 26 27 28 29 70 71 72 73 74 75 76 77
78 79 120 121 122 123 124 125 126 127 128 129]
#4 교차 검증 정확도 : 0.9667, 학습 데이터 크기 : 120, 검증 데이터 크기 : 30
#4 검증 세트 인덱스 [ 30 31 32 33 34 35 36 37 38 39 80 81 82 83 84 85 86 87
88 89 130 131 132 133 134 135 136 137 138 139]
#5 교차 검증 정확도 : 1.0, 학습 데이터 크기 : 120, 검증 데이터 크기 : 30
#5 검증 세트 인덱스 [ 40 41 42 43 44 45 46 47 48 49 90 91 92 93 94 95 96 97
98 99 140 141 142 143 144 145 146 147 148 149]
교차검증별 정확도 : [0.9667 0.9667 0.9 0.9667 1. ]
## 평균 검증 정확도 : 0.9600200000000001
교차 검증을 간편하게 해주는 API¶
1. cross_val_score()¶
cross_val_score(estimator , X , y=None, scoring=None, cv=None, n_jobs=1, verbose=0, fit_params=None, pre_dispatch='2*n_jobs')
-estimator : 분류 / 회귀 -X : 피처 데이터 셋 -y : 레이블 데이터 셋 -scoring : 예측 성능 평가 지표 -cv : 교차 검증 폴드 수
분류 : stratifiedKFold 로 /회귀 : KFold로
2. cross_validate()¶
cross_val_score 와 비슷하지만 여러가지 예층 성능 평가 지표를 반환 할 수 있다
3. GridSearchCV¶
최적의 파라미터를 찾아준다 GridSearchCV(estimator, param_grid, scoring, cv, refit) -estimator : 분류/회귀 -param_grid : {key+리스트} ; estimator 의 튜닝을 위해 파라미터명 과 파라미터값
-scoring : 성능평가지표 -cv : 교차 검증 폴드 수 -refit : True=최적의 파라미터가 찾아지면 찾은 값으로 재예측
# GridSearchCV
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV
# 데이터 로딩 > 데이터 분리
iris = load_iris()
# iris.data 는 데이터 세트에서 피처만으로 된 데이터를 넘파이로 가지고 있따
iris_data = iris.data
# iris.target 붓꽃 데이터 세트에서 레이블(결정값) 데이터를 넘파이로 가지고 있다
iris_label = iris.target
X_train, X_test, y_train, y_test = train_test_split(iris_data
, iris_label
, test_size=0.2
, random_state=121)
dtree_clf = DecisionTreeClassifier()
# 파라미터 세트 딕셔너리 형태로 생성
parameters = {'max_depth':[1,2,3] , 'min_samples_split':[2,3]}
import pandas as pd
# param_grid 의 하이퍼 파라미터를 3개의 train, test set fold로 나누어 테스트 수행 설정
grid_dtree = GridSearchCV(dtree_clf, param_grid=parameters, cv=3, refit=True)
# 학습데이터로 param_grid 의 하이퍼 파라미터를 순차적으로 학습(모델생성).평가
grid_dtree.fit(X_train, y_train)
# GridSearchCV 결과 데이터프레임으로 변환
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 |
# 최적의 파라미터 확인 후 속성에 기록된 최적의 파라미터와 결과값으로 재예측
# grid_dtree.best_params_
# grid_dtree.best_scores_
estimator = grid_dtree.best_estimator_
# GridSearchCV 의 .best_estimator_ 는 이미 최적 학습이 되어있으므로 별도 학습 필요 없음
pred = estimator.predict(X_test)
print('\n 검증별 정확도 : {0:.4f}'.format(accuracy_score(y_test, pred)))
검증별 정확도 : 0.9667
데이터 전처리¶
1.레이블 인코딩¶
선형회귀에서는 쓰일 수 없다- 숫자로 인식하여 가중치 부여가 될 수 있기 때문 대신, 트리 계열에서는 사용 가능 인미 1, 건형 2, 태석 3,... 이렇게 각 문자값에 숫자로 레이블 해준다.
2. 원-핫 인코딩¶
행 형태피처의 고유값을 열 형태로 차원을 변환(레이블인코딩)한 뒤, 고유값에 해당하는 칼럼에만 1을 표시 나머지 0으로 처리
pd.get_dummies(df) 사용하면 숫자형 값으로 변환 없이도 바로 변환 가능
3. 데이터 정규화¶
3-1 StandardScaler¶
3-2 MinMaxScaler¶
# 원-핫 인코딩
from sklearn.preprocessing import OneHotEncoder,LabelEncoder
import numpy as np
team =['건형','태석','승필','수병','동일','수빈','예지','민지']
# 레이블 인코딩(문자열 값을 숫자로 변환)
encoder = LabelEncoder()
encoder.fit(team)
# 숫자화 한 것을 열 형태로 변환
labels = encoder.transform(team)
# 2차원으로 변환
labels= labels.reshape(-1, 1)
# 원-핫 인코딩
oh_encoder = OneHotEncoder()
oh_encoder.fit(labels)
oh_labels = oh_encoder.transform(labels)
print('원핫 인코딩 데이터')
print(oh_labels.toarray())
print('원핫 인코딩 데이터 차원 ')
print(oh_labels.shape)
원핫 인코딩 데이터
[[1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 1. 0. 0. 0. 0. 0.]]
원핫 인코딩 데이터 차원
(8, 8)
import pandas as pd
df = pd.DataFrame({
'team':['건형','태석','승필','수병','동일','수빈','예지','민지']
})
pd.get_dummies(df)
team_건형 | team_동일 | team_민지 | team_수병 | team_수빈 | team_승필 | team_예지 | team_태석 | |
---|---|---|---|---|---|---|---|---|
0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
3 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 |
4 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 |
5 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
6 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
7 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
# StandardScaler
from sklearn.datasets import load_iris
import pandas as pd
# 데이터를 데이터프레임으로 변환
iris = load_iris()
iris_data = iris.data
iris_df = pd.DataFrame(data=iris_data, columns=iris.feature_names)
from sklearn.preprocessing import StandardScaler
# ss 객체 생성
scaler = StandardScaler()
# ss 로 데이터 셋 변환
scaler.fit(iris_df)
iris_scaled = scaler.transform(iris_df)
# transform() 적용으로 ndarray 형태로 반환되기 때문에 다시 데이터프레임으로 변환
iris_df_scaled = pd.DataFrame(data=iris_scaled, columns=iris.feature_names)
#확인
print('피쳐들의 평균 값')
print(iris_df_scaled.mean())
print('피쳐들의 분산 값')
print(iris_df_scaled.var())
피쳐들의 평균 값
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
피쳐들의 분산 값
sepal length (cm) 1.006711
sepal width (cm) 1.006711
petal length (cm) 1.006711
petal width (cm) 1.006711
dtype: float64
'머신러닝' 카테고리의 다른 글
[파이썬 머신러닝] 4장. 신용카드 사기 검출 (0) | 2021.01.19 |
---|---|
[파이썬 머신러닝] 4장. 산탄데르 고객 예측 (0) | 2021.01.19 |
[파이썬 머신러닝] 4장. 결정트리 (0) | 2021.01.14 |
[파이썬 머신러닝] 3장. 당뇨병 예측 (0) | 2021.01.14 |
[파이썬 머신러닝] 2장. 타이타닉 생존자 예측 (0) | 2021.01.14 |