본문으로 건너뛰기
Minsing Log
뒤로 가기

Supervised Learning(Classification)

Data & ML

Classification

Classification이란?

주어진 입력 값이 어떤 클래스에 속할지에 대한 결괏값을 도출하는 AI




모델종류

  1. 트리 구조 기반
  1. 확률 모델 기반
  1. 결정 경계 기반
  1. 신경망




Decision Tree model structure

DecisionTree란?

Impurity(불순도)

불순도란?

Impurity 측정 방법 - Gini Impurity

지니 계수(Gini Index) 해당 구역 안에 특정 클래스에 속하는 데이터의 비율을 모두 제외한 값, 다양성을 계산하는 방법

지니 불순도 예제를 보고 참고해보자

DecsionTree depth의 trade-off

cf) overfitting

DTmodel = DecisionTreeClassifier(max_depth=5)
DTmodel.fit(train_X, train_Y)
# max depth를 하이퍼파라미터튜닝할때는 오버피팅이되는가를 따로 체크해봐야함.

DecisionTree특징




Logistic Regression

Logistic Regression이란?

Binary Classification problem을 해결하기 위한 model이다. 최소값 0, 최대값 1로 결과값을 수렴시키기 위해 sigmoid(logistic) 함수 사용한다.

cf) sigmoid함수

cf2) Decision Boundary

Logistic Regression 왜 사용?

일반적은 Regression algorithm은 classification problem에 그대로 사용할 수 없기 때문에 해당 class에 속할 확률인 0 또는 1사이의 값만 내보낼 수 있도록 Linear Regression을 수정한다.

Logistic Regression 특징




Support Vector Machine(SVM)

최적의 Decision Boundary

Support Vector란?

Margin

svm 특징




Naive Bayes Classification

cf) 베이즈 정리란?

예시-스팸 메일

구현

1. 각각 구하기

import numpy as np

"""
1. "확인" 이라는 키워드가 등장했을 때 
    해당 메일이 스팸 메일인지 정상 메일인지
    판별하기 위한 함수를 구현합니다.
"""
def bayes_theorem():
    # 1. P(“스팸 메일”) 의 확률을 구하세요.
    p_spam = float(8/20)
    
    # 2. P(“확인” | “스팸 메일”) 의 확률을 구하세요.
    p_confirm_spam = float(5/8)
    
    # 3. P(“정상 메일”) 의 확률을 구하세요.
    p_ham = float(12/20)
    
    # 4. P(“확인” | "정상 메일" ) 의 확률을 구하세요.
    p_confirm_ham = float(2/12)
    
    # 5. P( "스팸 메일" | "확인" ) 의 확률을 구하세요.
    p_spam_confirm = float(5/7)
    
    # 6. P( "정상 메일" | "확인" ) 의 확률을 구하세요.
    p_ham_confirm = float(2/7)
    
    return p_spam_confirm, p_ham_confirm

def main():
    
    p_spam_confirm, p_ham_confirm = bayes_theorem()
    
    print("P(spam|confirm) = ",p_spam_confirm, "\nP(ham|confirm) = ",p_ham_confirm, "\n")
        
    # 두 값을 비교하여 확인 키워드가 스팸에 가까운지 정상 메일에 가까운지 확인합니다.
    value = [p_spam_confirm, p_ham_confirm]
    
    if p_spam_confirm > p_ham_confirm:
        print( round(value[0] * 100, 2), "% 의 확률로 스팸 메일에 가깝습니다.")
    else :
        print( round(value[1] * 100, 2), "% 의 확률로 일반 메일에 가깝습니다.")


if __name__ == "__main__":
    main()

2. 라이브러리 활용

from sklearn.datasets import load_wine

from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score

"""
1. 데이터를 불러오고, 
   불러온 데이터를 학습용, 테스트용 데이터로 
   분리하여 반환하는 함수를 구현합니다.
   
   Step01. 사이킷런에 저장되어 있는 데이터를 
           (X, y) 형태로 불러옵니다.
   
   Step02. 불러온 데이터를 
           학습용 데이터와 테스트용 데이터로 분리합니다.
           
           학습용 데이터 : 80%, 테스트용 데이터 : 20%, 
           
           일관된 결과 확인을 위해 random_state를 
           0 으로 설정합니다.
"""
def load_data():
    
    X, y = load_wine(return_X_y = True)
    
    print("데이터 확인해보기 :\n", X[:1])
    
    train_X, test_X, train_y, test_y = train_test_split(X,y, test_size=0.20, random_state = 0)
    
    return train_X, test_X, train_y, test_y
    
"""
2. 가우시안 나이브 베이즈 모델을 불러오고,
   학습을 진행한 후 테스트 데이터에 대한 
   예측값을 반환하는 함수를 구현합니다.
   
   Step01. 가우시안 나이브 베이즈 모델을 정의합니다.
   
   Step02. 학습용 데이터에 대해 모델을 학습시킵니다.
   
   Step03. 테스트 데이터에 대한 모델 예측을 수행합니다.
"""
def Gaussian_NB(train_X, test_X, train_y, test_y):
    
    model = GaussianNB()
    
    model.fit(train_X,train_y)
    
    predicted = model.predict(test_X)
    
    return predicted
    
# 데이터 불러오기, 모델 예측 결과를 확인할 수 있는 함수입니다.
def main():
    
    train_X, test_X, train_y, test_y = load_data()
    
    predicted = Gaussian_NB(train_X, test_X, train_y, test_y)
    
    ## 모델 정확도를 통해 분류 성능을 확인해봅니다.
    print("\nModel Accuracy : ")
    print(accuracy_score(test_y, predicted))

if __name__ == "__main__":
    main()

코드출처: 2022 군 장병 swai역량 강화 중급 프로젝트 과정

특징




KNN(K-Nearest Neighbor)

원리

특징

cf) knn과 kmeans 는 classification과 clustering이라는 목적에서 차이가 있다. 보충설명 링크: https://velog.io/@jhlee508/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D-K-%ED%8F%89%EA%B7%A0K-Means-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98





평가지표

종류

Confusion matrix

True Positive: 실제 Positive인 값을 Positive라고 예측(정답) True Negative: 실제 Negative인 값을 Negative라고 예측(정답)

False Positive: 실제 Negative인 값을 Positive라고 예측(오답) - 1형 오류 False Negative: 실제 Positive인 값을 Negative라고 예측(오답) - 2형 오류



Accuracy

- 용도: 모델이 얼마나 정확하게 분류했는가?



Precision & Recall


#### Precision


Recall/TPR

출처 1)첫번째 decision tree 구조 사진: 2022 군장병 sw/ai 역량 강화 프로그램 분류 단원 https://military22.elice.io/courses/26526/lectures/204994/materials/12 2)내용참조:2022 군장병 sw/ai 역량 강화 프로그램 분류 단원 3)Confusion matrix 사진 : https://eunsukimme.github.io/ml/2019/10/21/Accuracy-Recall-Precision-F1-score/ 4)Accuracy 수식 사진:https://wooono.tistory.com/232 5)precision 수식: https://ctkim.tistory.com/79 6)recall 수식: http://www.gisdeveloper.co.kr/?p=8146 7)꼬지모 사진출처:https://pokemon.fandom.com/ko/wiki/%EA%BC%AC%EC%A7%80%EB%AA%A8_(%ED%8F%AC%EC%BC%93%EB%AA%AC) 8)SVM 모델 사진 https://hleecaster.com/ml-svm-concept/ 9)Logistic Regression 모델 설명 사진들: 2022 군장병 sw/ai 역량 강화 프로그램 분류 단원 https://military22.elice.io/courses/26528/lectures/204997/materials/13 10)Support Vector 사진: https://sjpyo.tistory.com/m/40 11)hard/soft margin: https://ankitnitjsr13.medium.com/math-behind-svm-support-vector-machine-864e58977fdb

공개 여정 구독

글이 올라오면 이메일로 보내드릴게요.

개발, 창업, 배움, 실패와 회고를 짧고 솔직하게 기록합니다. 검색으로 스쳐가는 독자가 아니라 여정을 따라오는 팬을 만들기 위한 뉴스레터입니다.

뉴스레터는 준비 중입니다. 그동안 RSS 로 구독하거나 이메일 로 알림을 요청해 주세요.


이 글 공유하기:

댓글

GitHub 계정으로 로그인해 댓글을 남길 수 있습니다.


이전 글
Overfitting & Underfitting
다음 글
Supervised Learning(Regression)