[머신러닝] scikit-learn 분류 모델

yenaryu·2022년 1월 6일

문제지

머신러닝 모델에게 입력되는 데이터. feature라고 부르기도 한다. 변수 이름으로는 X를 많이 사용한다.

정답지

머신러닝 모델이 맞혀야 하는 데이터. label 또는 target이라고 부르기도 한다. 변수 이름으로는 y를 많이 사용한다.


머신러닝 모델 학습을 위한 데이터셋 분리

  • training dataset : 학습에 사용
  • test dataset : 모델의 성능을 평가하는 데 사용

지도학습 (Supervised Learning) : 지도받을 수 있는, 정답이 있는 문제에 대해 학습하는 것

  • 분류(Classification) : 입력받은 데이터를 특정 카테고리 중 하나로 분류해내는 문제
  • 회귀(Regression) : 입력받은 데이터에 따라 특정 필드의 수치를 맞히는 문제

비지도 학습 (Unsupervised Learning) : 정답이 없는 문제를 학습하는 것


Decision Tree 모델

의사 결정을 할, 즉 데이터를 분리할 어떤 경계를 찾아내어 데이터를 체에 거르듯 한 단계씩 분류해나가는 모델


scikit-learn 실습

#모듈 import
from sklearn.datasets import load_iris  #(2)sklearn라이브러리에 detasets패키지 모듈 import
from sklearn.model_selection import train_test_split  #(3)sklearn.model_selection패키지의 train_test_split를 활용해 데이터셋 분리
from sklearn.tree import DecisionTreeClassifier #(4)sklearn.tree패키지에 DecisionTreeClassifier import
from sklearn.metrics import classification_report

#(2)데이터 준비
iris = load_iris() #lord_iris import
iris_data = iris.data #중요 데이터 iris_data 변수에 저장 후 데이터 크기 확인
iris_label = iris.target #iris_label변수에 iris 데이터의 target저장

#(3)train, test 데이터 분리
 #X:feature데이터만 / y:정답label데이터만 
 #X데이터셋을 머신러닝 모델에 입력 -> 모델이 내뱉는 품종 예측 결과를 정답 y와 비교하여 학습
X_train, X_test, y_train, y_test = train_test_split(iris_data,  #feature(입력받는 특징 데이터)
                                                    iris_label,  #label(모델이 맞춰야하는 정답값)
                                                    test_size=0.2,  #test dataset 크기 조절(0.2=전체 20%를 test데이터로 사용)
                                                    random_state=7  #train데이터와 test데이터 분리시 적용되는 랜덤성)


# (4)decision tree 모델 학습 및 예측
decision_tree = DecisionTreeClassifier(random_state=32) #decision_tree변수에 모델 저장
decision_tree.fit(X_train, y_train) #fit메서드로 모델 학습
y_pred = decision_tree.predict(X_test)

print(classification_report(y_test, y_pred))

다른 모델 응용해보기

Random Forest

상위 모델들이 예측하는 편향된 결과보다, 다양한 모델들의 결과를 반영함으로써 더 다양한 데이터에 대한 의사결정을 내릴 수 있게 함.

  1. 건강의 위험도를 예측하기 위해서는 많은 요소를 고려 성별, 키, 몸무게, 지역, 운동량, 흡연유무, 음주 여부, 혈당, 근육량, 기초 대사량 등 수많은 요소가 필요
  2. Feature가 30개라 했을 때 30개의 Feature를 기반으로 하나의 결정 트리를 만든다면 트리의 가지가 많아질 것이고, 이는 오버피팅의 결과를 야기
  3. 30개의 Feature 중 랜덤으로 5개의 Feature만 선택해서 하나의 결정 트리 생성
  4. 계속 반복하여 여러 개의 결정 트리 생성
  5. 여러 결정 트리들이 내린 예측 값들 중 가장 많이 나온 값을 최종 예측값으로 지정
  6. 이렇게 의견을 통합하거나 여러 가지 결과를 합치는 방식을 앙상블(Ensemble)이라고 함
  7. 하나의 거대한 (깊이가 깊은) 결정 트리를 만드는 것이 아니라 여러 개의 작은 결정 트리를 만드는 것
  8. 분류 : 여러 개의 작은 결정 트리가 예측한 값들 중 가장 많은 값, 회귀 : 평균
from sklearn.ensemble import RandomForestClassifier

X_train, X_test, y_train, y_test = train_test_split(iris_data, 
                                                    iris_label, 
                                                    test_size=0.2, 
                                                    random_state=21)

random_forest = RandomForestClassifier(random_state=32)
random_forest.fit(X_train, y_train)
y_pred = random_forest.predict(X_test)

print(classification_report(y_test, y_pred))

Support Vector Machine (SVM)
Support Vector와 Hyperplane(초평면)을 이용해서 분류를 수행하게 되는 대표적인 선형 분류 알고리즘

from sklearn import svm

svm_model = svm.SVC()
svm_model.fit(X_train, y_train)
y_pred = svm_model.predict(X_test)

print(classification_report(y_test, y_pred))

Stochastic Gradient Descent Classifier (SGDClassifier)
배치 크기가 1인 경사하강법 알고리즘. 즉, 확률적 경사하강법은 데이터 세트에서 무작위로 균일하게 선택한 하나의 예를 의존하여 각 단계의 예측 경사를 계산

from sklearn.linear_model import SGDClassifier

sgd_model = SGDClassifier()
sgd_model.fit(X_train, y_train)
y_pred = sgd_model.predict(X_test)

print(classification_report(y_test, y_pred))

Logistic Regression
소프트맥스(softmas) 함수를 사용한 다중 클래스 분류 알고리즘
이름은 회귀지만, 실제로는 분류를 수행

from sklearn.linear_model import LogisticRegression

logistic_model = LogisticRegression()
logistic_model.fit(X_train, y_train)
y_pred = logistic_model.predict(X_test)

print(classification_report(y_test, y_pred))

성능 평가 : 정확도(Accuracy)확인

from sklearn.metrics import accuracy_score

accuracy = accuracy_score(y_test, y_pred)
accuracy

> 0.933333 #90%의 정확도

실습
digits_data와 new_label로 Decision Tree 모델을 학습시키고, 정확도를 확인해 보세요

from sklearn.metrics import accuracy_score #정확도
from sklearn.model_selection import train_test_split #데이터 분리
from sklearn.tree import DecisionTreeClassifier #모델학습

X_train, X_test, y_train, y_test = train_test_split(digits_data,
                                                    new_label,
                                                    test_size=0.2,
                                                    random_state=15)

decision_tree = DecisionTreeClassifier(random_state=15)
decision_tree.fit(X_train, y_train)
y_pred = decision_tree.predict(X_test)

accuracy = accuracy_score(y_test, y_pred)
accuracy   

>0.9388888 #93.9%의 성능

오차 행렬(confusion matrix)

  • TP(True Positive) : 실제 환자에게 양성판정 (참 양성)
  • FN(False Negative) : 실제 환자에게 음성판정 (거짓 음성)
  • FP(False Positive) : 건강한 사람에게 양성판정 (거짓 양성)
  • TN(True Negative) : 건강한 사람에게 음성판정 (참 음성)

TP는 높고 FP또는 FN이 낮을수록 좋은 예측이므로, Precision과 Recall 값이 클수록 좋다

Precision은 분모에 있는 FP가 낮을수록 커짐. 음성인데 양성으로 판단하는 경우가 적어야 함. 음성을 놓치면 안됨 (ex)스팸 메일 처리(음성:정상메일, 양성:스팸메일)
Recall은 분모에 있는 FN이 낮을수록 커짐. 양성인데 음성으로 판단하는 경우가 적어야 함. 양성을 놓치면 안됨 (ex) Covid검사, 암환자 진단

from sklearn.metrics import confusion_matrix  #오차행렬은 sklearn.metircs 패키지 내 confusion_matrix로 확인 가능

confusion_matrix(y_test, y_pred)

> array([[320,  13], #TP FN
       [  9,  18]])  #FP TN
# Precision, Recall, F1 score 지표 한눈에 확인
from sklearn.metrics import classification_report

print(classification_report(y_test, y_pred))

📆 2022-01-06

0개의 댓글