まとめ
- Naive Bayes สมมติว่าฟีเจอร์เป็นอิสระต่อกันภายใต้คลาสเดียวกัน แล้วใช้ทฤษฎีเบย์ผสานความน่าจะเป็นล่วงหน้ากับความน่าจะเป็นตามเงื่อนไข
- ฝึกและทำนายรวดเร็ว เหมาะกับงานข้อความหรือข้อมูลมิติสูงที่เบาบาง ใช้เป็น baseline ที่แข็งแรงได้
- การใช้ Laplace smoothing หรือ TF-IDF ช่วยรับมือคำที่ไม่เคยเห็นและความแตกต่างด้านความถี่
- หากสมมติฐานอิสระแรงเกินไป สามารถเลือกฟีเจอร์หรือผสมกับโมเดลอื่นในลักษณะ ensemble
ภาพรวมเชิงสัญชาติญาณ #
ทฤษฎีเบย์ให้ความสัมพันธ์ระหว่าง prior, likelihood และ posterior หากเชื่อว่าฟีเจอร์เป็นอิสระเมื่อทราบคลาส ก็สามารถประมาณ likelihood ด้วยผลคูณของโพรบแต่ละฟีเจอร์ ทำให้เรียนรู้จากข้อมูลจำนวนน้อยได้
สูตรสำคัญ #
สำหรับคลาส \(y\) และเวกเตอร์คุณลักษณะ \(\mathbf{x}=(x_1,\ldots,x_d)\)
$$ P(y \mid \mathbf{x}) \propto P(y) \prod_{j=1}^{d} P(x_j \mid y). $$
งานข้อความนิยมใช้ Multinomial Naive Bayes (นับจำนวนคำ), Bernoulli Naive Bayes (มี/ไม่มีคำ) หรือ Gaussian Naive Bayes สำหรับข้อมูลต่อเนื่อง
ทดลองด้วย Python #
ตัวอย่างต่อไปนี้ใช้ Gaussian Naive Bayes กับข้อมูลสังเคราะห์ 3 คลาส แล้ววาดบริเวณการจำแนก
from __future__ import annotations
import japanize_matplotlib
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_classification
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.naive_bayes import GaussianNB
def run_naive_bayes_demo(
n_samples: int = 600,
n_classes: int = 3,
random_state: int = 0,
title: str = "บริเวณการจำแนกของ Gaussian Naive Bayes",
xlabel: str = "คุณลักษณะที่ 1",
ylabel: str = "คุณลักษณะที่ 2",
) -> dict[str, float | np.ndarray]:
"""Train Gaussian Naive Bayes on synthetic data and plot decision regions."""
japanize_matplotlib.japanize()
X, y = make_classification(
n_samples=n_samples,
n_features=2,
n_informative=2,
n_redundant=0,
n_clusters_per_class=1,
n_classes=n_classes,
random_state=random_state,
)
clf = GaussianNB()
clf.fit(X, y)
accuracy = float(accuracy_score(y, clf.predict(X)))
conf = confusion_matrix(y, clf.predict(X))
x_min, x_max = X[:, 0].min() - 1.0, X[:, 0].max() + 1.0
y_min, y_max = X[:, 1].min() - 1.0, X[:, 1].max() + 1.0
grid_x, grid_y = np.meshgrid(
np.linspace(x_min, x_max, 400),
np.linspace(y_min, y_max, 400),
)
grid = np.c_[grid_x.ravel(), grid_y.ravel()]
preds = clf.predict(grid).reshape(grid_x.shape)
fig, ax = plt.subplots(figsize=(7, 6))
ax.contourf(
grid_x,
grid_y,
preds,
alpha=0.25,
cmap="coolwarm",
levels=np.arange(-0.5, n_classes + 0.5, 1),
)
ax.scatter(X[:, 0], X[:, 1], c=y, cmap="coolwarm", edgecolor="k", s=25)
ax.set_title(title)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
fig.tight_layout()
plt.show()
return {"accuracy": accuracy, "confusion": conf}
metrics = run_naive_bayes_demo(
title="บริเวณการจำแนกของ Gaussian Naive Bayes",
xlabel="คุณลักษณะที่ 1",
ylabel="คุณลักษณะที่ 2",
)
print(f"ความแม่นยำขณะฝึก: {metrics['accuracy']:.3f}")
print("เมทริกซ์ความสับสน:")
print(metrics["confusion"])

เอกสารอ้างอิง #
- Manning, C. D., Raghavan, P., & Schütze, H. (2008). Introduction to Information Retrieval. Cambridge University Press.
- Murphy, K. P. (2012). Machine Learning: A Probabilistic Perspective. MIT Press.