2-1. Tutorial - 붗꽃 품종 예측하기
In [1]:
from IPython.core.display import display, HTML
display(HTML("<style> .container{width:90% !important;}</style>"))

2-1. Tutorial - 붗꽃 품종 예측하기

붗꽃 데이터 세트로 붓꽃의 품종을 분류하는 예제 데이터 세트를 사이킷런에서 받아 간단한 머신러닝 구현

  • 꽃잎의 길이, 너비 꽆받침의 길이와 너비를 Feature로 꽃의 품종을 예측
In [2]:
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
import pandas as pd
In [3]:
# 붓꽃 데이터 세트를 로딩
iris = load_iris()

# iris.data는 Iris 데이터 세트에서 feature만으로 된 데이터를 numpy로 가지고 있습니다.
iris_data = iris.data

# iris.target은 붓꽃 데이터 세트에서 레이블(결정 값) 데이터를 numpy로 가지고 있습니다.
iris_label = iris.target
print('iris target값: ', iris_label)
print('iris target명: ', iris.target_names)

# 붓꽃 데이터 세트를 자세히 보기 위해 DataFrame으로 변환합니다.
iris_df = pd.DataFrame(data=iris_data, columns=iris.feature_names)
iris_df ['label'] = iris.target
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']
Out[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
  • Feature : sepal length (cm), sepal width (cm), petal length (cm), petal width (cm)
  • Target(Label) : 0 - 'setosa', 1 - 'versicolor', 2-'virginica'
  • Iris 데이터를 학습용 데이터와 테스트용 데이터를 분리
    → 학습 데이터로 학습한 모델의 성능 측정용으로 테스트 세트 사용

  • train_test_split(피처데이터셋, 라벨 데이터셋, test_size =값 , random_state = 값 )
    → test_size 입력 값의 비율로 데이터를 쉽게 분할

In [4]:
X_train, X_test, y_train, y_test = train_test_split(iris_data, iris_label, test_size=0.2, random_state=11)

학습 데이터를 확보했으니 이를 기반으로 Decision Tree를 활용하여 학습과 예측

In [5]:
# DecisionTreeClassifier 객체 생성
dt_clf = DecisionTreeClassifier(random_state=11)

# 학습수행
dt_clf.fit(X_train, y_train)
Out[5]:
DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None,
            max_features=None, max_leaf_nodes=None,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, presort=False, random_state=11,
            splitter='best')

예측은 반드시 학습 데이터가 아닌 다른 데이터를 이용하며 일반적으로 테스트 데이터 세트를 이용

predict()에 테스트용 피처데이터를 입력하여 예측 값을 반환

In [6]:
# 학습이 완료된 DecisionTreeClassifier 객체에서 테스트 데이터 세트로 예측 수행
y_pred = dt_clf.predict(X_test)

학습된 모델에 대한 예측 성능을 평가 : iris 데이터셋에서는 이번에 정확도로 측정

accuracy_score(실제 레이블 세트, 예측 레이블 세트) : 정확도를 측정하기 위한 사이킷런의 함수

In [7]:
from sklearn.metrics import accuracy_score
print('예측정확도 : {0: .4f}'.format(accuracy_score(y_test, y_pred)))
예측정확도 :  0.9333

학습한 DecisionTree의 정확도가 0.9333으로 측정

정리 : 예측 프로세스


(1) 데이터 세트 분리 : 학습데이터와 테스트데이터로 분리 (train_test_split())

(2) 모델 학습 : 학습데이터를 기반으로 머신러닝 알고리즘을 적용하여 모델을 학습

(3) 예측 수행 : 학습된 모델을 이용하여 테스트 데이터의 분류를 예측

(4) 평가 : 예측 결과값과 실제 결과값을 비교하여 모델 성능을 평가

In [ ]:
 

+ Recent posts