1 minute read

8.6 Naive Bayes

- Concept and Definition of Naive Bayes

서로 조건부 독립(conditional independence)인 피처를 가정하고, 베이즈 이론을 기반으로 하는 머신러닝 알고리즘

- 작동 방식

feature data를 조건부 확률에서 ‘조건’이라고 가정하고, 알고싶은 ‘사건’의 확률을 추정한다.

여러가지 ‘feature’,’조건’을 가정한 조건부 확률은 조건이 하나인 작고 여러개의 조건부 확률로 나눌 수 있음

ex) P(배드민턴 = Y|날씨 = 맑음, 바람 = 약함, 온도 = 보통)

~ P(날씨 = 맑음|배드민턴 = Y)P(바람 = 약함|배드민턴 = Y)P(온도 = 보통|배드민턴 = Y)

- Naive Bayes practice

from sklearn import datasets
raw_wine = datasets.load_wine()
X = raw_wine.data
y = raw_wine.target

from sklearn.model_selection import train_test_split
X_tn, X_te, y_tn, y_te = train_test_split(X,y,random_state=0)

from sklearn.preprocessing import StandardScaler
std_scale = StandardScaler()
std_scale.fit(X_tn)
X_tn_std = std_scale.transform(X_tn)
X_te_std = std_scale.transform(X_te)

# 나이브 베이즈를 사용하기 위해 필요한 GaussianNB 함수를 불러온다
from sklearn.naive_bayes import GaussianNB
clf_gnb = GaussianNB()
clf_gnb.fit(X_tn_std,y_tn)

# 데이터 예측
pred_gnb = clf_gnb.predict(X_te_std)
print(pred_gnb)

# 모델 평가

# recall 평가
from sklearn.metrics import recall_score
recall = recall_score(y_te, pred_gnb, average='macro')
print(recall)

# confusion matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_te,pred_gnb)
print(cm)

# class- report
from sklearn.metrics import classification_report
cr = classification_report(y_te,pred_gnb)
print(cr)



[0 2 1 0 1 1 0 2 1 1 2 2 0 0 2 1 0 0 2 0 0 0 0 1 1 1 1 1 1 2 0 0 1 0 0 0 2
 1 1 2 0 0 1 1 1]
0.9523809523809524
[[16  0  0]
 [ 2 18  1]
 [ 0  0  8]]
              precision    recall  f1-score   support

           0       0.89      1.00      0.94        16
           1       1.00      0.86      0.92        21
           2       0.89      1.00      0.94         8

    accuracy                           0.93        45
   macro avg       0.93      0.95      0.94        45
weighted avg       0.94      0.93      0.93        45