
📌 특징
나이브 베이즈는 베이즈 정리를 기반:
✅ 설명
📝 쉽게 정리하면
사후 확률(Posterior) = 사전 확률(Prior) × 가능도(Likelihood) ÷ 증거(Evidence)
| 날씨 | 비 옴 (☔) | 비 안 옴 | 합계 |
|---|---|---|---|
| 맑은 날 ☀ | 3 | 7 | 10 |
| 흐린 날 ☁ | 5 | 5 | 10 |
| 합계 | 8 | 12 | 20 |
사전 확률 (Prior Probability)
가능도 (Likelihood) - 특정 날씨일 때 비가 올 확률
증거 (Evidence)
사후 확률 (Posterior Probability)
즉, 날씨가 맑을 때 비가 올 확률은 35%
나이브 베이즈는 데이터의 특성에 따라 여러 변형이 있습니다.
📌 사용 예시: 키, 몸무게, 온도 등 연속형 데이터 분류
📌 사용 예시: 이메일 스팸 분류, 뉴스 카테고리 분류
📌 사용 예시: 텍스트 분류(문서에 특정 단어가 있는지 없는지)
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
# 데이터 불러오기
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)
# 가우시안 나이브 베이즈 모델 생성 및 학습
gnb = GaussianNB()
gnb.fit(X_train, y_train)
# 예측 및 평가
accuracy = gnb.score(X_test, y_test)
print(f'Accuracy: {accuracy:.2f}')
✅ 장점
❌ 단점
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
data = load_iris()
X = data.data # 특성 데이터
y = data.target # 라벨 데이터
feature = data.feature_names # 특성 이름 리스트
load_iris() : 사이킷런에서 제공하는 붓꽃(Iris) 데이터셋 로드X : 입력 변수 (꽃잎과 꽃받침의 길이 및 너비)y : 타겟 변수 (0: Setosa, 1: Versicolor, 2: Virginica)feature : 각 피처의 이름param_grid = {'var_smoothing': np.logspace(0, -9, num=100)}
gnb = GaussianNB()
grid_search = GridSearchCV(gnb, param_grid, cv=5, scoring='accuracy')
grid_search.fit(X, y)
var_smoothing: 가우시안 나이브 베이즈의 분산 스무딩(variance smoothing) 계수를 최적화하는 하이퍼파라미터np.logspace(0, -9, num=100): 에서 까지 100개의 값 생성GridSearchCV(gnb, param_grid, cv=5, scoring='accuracy')var_smoothing 찾기accuracy(정확도)를 기준으로 성능 평가best_gnb = grid_search.best_estimator_ # 최적 모델
y_pred = best_gnb.predict(X) # 모델 예측값
accuracy = accuracy_score(y, y_pred) # 정확도 계산
print('Best estimates found', grid_search.best_params_)
print(f'Model Accuracy : {accuracy : .4f}')
grid_search.best_estimator_ : 최적의 하이퍼파라미터를 적용한 가우시안 나이브 베이즈 모델accuracy_score(y, y_pred): 훈련 데이터에 대한 정확도 계산X)에 대해 평가하므로, 과적합(overfitting) 가능성이 존재함.train_test_split()을 사용하여 훈련/테스트 데이터로 나눈 후 검증해야 함.feature_importance = 1 / (best_gnb.var_).mean(axis=0)
importance_df = pd.DataFrame({'Feature': feature, 'Importance': feature_importance})
importance_df = importance_df.sort_values(by='Importance', ascending=False)
plt.figure(figsize=(10, 10))
sns.barplot(x="Importance", y="Feature", data=importance_df)
plt.title("Feature Importance (GaussianNB)")
plt.xlabel("Importance Score (1/var)")
plt.ylabel("Features")
plt.show()
out:

best_gnb.var_ : 가우시안 나이브 베이즈 모델의 각 피처별 분산1 / (best_gnb.var_).mean(axis=0) : 분산의 역수를 이용해 특성 중요도를 정의importance_df.sort_values(by='Importance', ascending=False): 중요도가 높은 순서로 정렬sns.barplot(x="Importance", y="Feature", data=importance_df): 피처 중요도를 바 플롯으로 시각화var_smoothing 최적화X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
grid_search.fit(X_train, y_train)
best_gnb = grid_search.best_estimator_
y_test_pred = best_gnb.predict(X_test)
test_accuracy = accuracy_score(y_test, y_test_pred)
print(f'Model Test Accuracy: {test_accuracy:.4f}')test_size=0.2 : 20% 데이터를 테스트용으로 사용