728x90
반응형
학습/테스트 데이터 세트 분리 - train_test_split()
# 학습/테스트 데이터 세트 분리 -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('예측 정확도 : ',accuracy_score(train_label, pred))
- 정확도가 100% 예측한 이유는 이미 학습한 학습 데이터 세트를 기반으로 예측했기 때문이다.
train_test_split()
- 첫 번째 파라미터 피처 데이터 세트
- 두 번째 파라미터 레이블 데이터 세트
- 선택적 파라미터
- test_size : 전체 데이터에서 학습용 데이터 세트 크기를 얼마로 샘플링할 것인가를 결정한다..
- shuffle : 데이터를 분리하기 전에 데이터를 미리 섞을지를 결정한다.
- random_state : random_state는 호출할 때마다 동일한 학습/테스트용 데이터 세트를 생성하기 위해 주어지는 난수 값
- 반환값은 튜플 형태다.
train_test_split() 활용
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)
# 학습 데이터 기반 예측 정확도 측정
dt_clf.fit(x_train, y_train)
pred = dt_clf.predict(x_test)
print('예측 정확도 : {0:.4f}'.format(accuracy_score(y_test, pred)))
교차 검증
- 본고사를 치르기 전에 모의고사를 여러 번 보는 것
- 대부분의 ML 모델의 성능 평가는 교차 검증 기반으로 1차 평가를 한 뒤에 최종적으로 테스트 데이터 세트에 적용해 평가하는 프로세스다.
- ML에 사용되는 데이터 세트를 세분화해서 학습, 검증, 테스트 데이터 세트로 나눌 수 있다.
K 폴드 교차 검증
- 가장 보편적으로 사용되는 교차 검증 기법
- K개의 데이터 폴드 세트를 만들어서 K번만큼 각 폴드 세트에 학습과 검증 평가를 반복적으로 수행하는 방법
- 5개의 폴드 세트로 분리
# K 폴드 교차 검증
# K = 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개
- 학습용 데이터 세트는 4/5인 120개
- 검증 테스트 데이터 세트는 1/5인 30개로 분할된다.
# 검증 인덱스 추출
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('\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))
- 교차 시마다 검증 세트의 인덱스가 달라짐
Stratified K 폴드
- 불균형한(imbalanced) 분포도를 가진 레이블(결정 클래스) 데이터 집합을 위한 K 폴드 방식
- 불균형한 분포도를 가진 레이블 데이터 집합은 특정 레이블 값이 특이하게 많거나 매우 적어서 값의 분포가 한쪽으로 치우치는 것을 말한다.
- K폴드가 레이블 데이터 집합이 원본 데이터 집합의 레이블 분포를 학습 및 테스트 데이터 세트에 제대로 분배하지 못하는 경우의 문제를 해결해 준다.
# Startified K 폴드
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()
# 학습, 검증 레이블 데이터 값의 분포도 확인
kfold = KFold(n_splits=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())
print()
StratifiedKFold 활용
# 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('## 교차 검증 : {0}'.format(n_iter))
print('학습 레이블 데이터 분포 : \n', label_train.value_counts())
print('검증 레이블 데이터 분포 : \n', label_test.value_counts())
print()
StratifiedKFold 이용해 데이터 분리
# 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))
- 회귀(Regression)에서는 Stratified K 폴드가 지원되지 않는다.
- 회귀의 결정값은 이산값 형태의 레이블이 아니라 연속된 숫자값이기 때문에 결정값별로 분포를 정하는 의미가 없기 때문이다.
교차 검증 간편하게 - cross_val_score()
- 다음 과정을 한꺼번에 해주는 API
- 폴드 세트를 설정
- for 루프에서 반복적으로 학습 및 테스트 데이터의 인덱스를 추출
- 반복적으로 학습과 예측을 수행하고 예측 성능을 반환
- 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가 주요 파라미터
- X = 피처 데이터 세트
- y = 레이블 데이터 세트
- scoring = 예측 성능 평가 지표를 기술
- cv = 교차 검증 폴드 수를 의미
# cross_val_score() 할용
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
# 성능 지표는 정확도(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))
- cross_val_score()는 단 하나의 평가 지표만 가능하지만, cross_validate()는 여러 개의 평가 지표를 반환할 수 있다.
GridSearchCV - 교차 검증과 최적 하이퍼 파라미터 튜닝을 한 번에
- 사이킷런은 GridSearchCV API를 이용해 Classifier나 Regression와 같은 알고리즘에 사용되는 하이퍼 파라미터를 순차적으로 입력하면서 최적의 파라미터를 도출할 수 있는 방안을 제공한다.
GridSearchCV 클래스 생성자 주요 파라미터
- estimator : classifier, regressor, pipeline이 사용 가능
- param_grid : key + 리스트 값을 가지는 딕셔너리가 주어진다. ertimator의 튜닝을 위해 파라미터명과 사용될 여러 파라미터 값을 지정
- scoring : 예측 성능을 측정할 평가 방법을 지정
- cv : 교차 검증을 위해 분할되는 학습/테스트 세트의 개수를 지정
- refit : 디폴트는 True, True 생성 시 가장 최적의 하이퍼 파라미터를 찾은 뒤 입력된 estimator 객체를 해당 하이퍼 파라미터로 재학습시킨다.
# GridSearchCV 이용
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV
# 데이터를 로딩하고 학습 데이터와 테스트 데이터 분리
iris_data = 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()
# 파라미터를 딕셔너리 형태로 설정
parameters = {'max_depth' : [1,2,3], 'min_samples_split' : [2,3]}
import pandas as pd
# param_Grid의 하이퍼 라마티러를 3개의 train, test set fold로 나누어 테스트 수행 설정
# result=True가 defual - True면 가장 좋은 파라미터 설정으로 재학습 시킨다.
grid_dtree = GridSearchCV(dtree, param_grid=parameters, cv=3, refit=True)
#붓꽃 학습 데이터로 param_grid 하이퍼 파라미터 순차적 학습/평가
grid_dtree.fit(x_train, y_train)
# 결과 추출 후 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']]
최적 파라미터, 최고 정확도 확인하기
# 최적 파라미터, 최고 정확도 확인
print('GridSearchCV 최적 파라미터 : ',grid_dtree.best_params_)
print('GridSearchCV 최고 정확도 : {0:.4f}'.format(grid_dtree.best_score_))
# 최적 성능 하이퍼 파라미터로 교체
estimator = grid_dtree.best_estimator_
# GridSearchCV의 best_estimator_는 이미 최적 학습이 됐으므로 별도 학습이 필요 없음
pred = estimator.predict(x_test)
print('테스트 데이터 세트 정확도 : {0:.4f}'.format(accuracy_score(y_test, pred)))
728x90
반응형
최근댓글