Overview
What is Naive Bayes?
Naive Bayes is a supervised learning technique. Predicts class probabilities using feature independence assumption. Its central idea is summarized by P(y | x₁,…,x_d) ∝ P(y) ∏ⱼ₌₁ᵈ P(xⱼ | y).
This guide connects theory to practice. You will trace the input, intermediate process, and output; decode the notation; run a dependency-light implementation; then repeat the workflow with scikit-learn and evaluate the result.
By the end of this tutorial, you will be able to
- Explain when Naive Bayes is appropriate and what assumptions it makes.
- Read its mathematical notation or complexity statement without guessing what the symbols mean.
- Follow and modify a from-scratch Python implementation.
- Build a practical workflow with scikit-learn and choose useful evaluation checks.
Preparation
Prerequisites and tools
You do not need an advanced software stack. Start with a recent Python environment and the fundamentals below, then install only the packages used by the practical example.
- Comfort with Python functions, NumPy arrays, and basic descriptive statistics.
- A clear distinction between training data, validation data, and untouched test data.
- Familiarity with features, targets, preprocessing, and task-appropriate evaluation metrics.
Process
How Naive Bayes works
- 1
Input
Numeric or categorical features and class labels.
- 2
Prepare and configure
Check shapes, value ranges, ordering assumptions, missing values, and the parameters that control the algorithm’s behavior.
- 3
Algorithm process
Calculate posterior probability from prior and likelihood.
- 4
Output
A probability distribution over classes.
- 5
Validate
Use log loss to assess probability quality in addition to classification accuracy.
Core concept
Formula and intuition
P(y) is the class prior; each P(xⱼ | y) is a feature likelihood, multiplied under the conditional-independence assumption.
The notation captures the main operation or complexity statement behind Naive Bayes. Read it together with the symbol key above and the step-by-step process in this guide.
Applications
When to use Naive Bayes
Text classification, spam filtering, and sentiment analysis.
Change one parameter at a time in the interactive lesson, replay the animation, and connect the visible change to the input, process, and output described above.
Implementation
Naive Bayes from scratch in Python
This dependency-light example emphasizes the algorithm’s mechanics so each important step remains visible.
import numpy as np
# two Gaussian-distributed classes
rng = np.random.default_rng(0)
X = np.vstack([rng.normal(-1, 1, (100, 2)), rng.normal(1, 1, (100, 2))])
y = np.array([0] * 100 + [1] * 100)
# estimate the mean and variance of each class, per feature, treating features as independent (naive)
stats = {}
for c in [0, 1]:
stats[c] = {"mean": X[y == c].mean(axis=0), "var": X[y == c].var(axis=0) + 1e-6,
"prior": np.mean(y == c)}
def log_likelihood(x, mean, var):
# log of the Gaussian probability density, summed across the independent features
return -0.5 * np.sum(np.log(2 * np.pi * var) + (x - mean) ** 2 / var)
def predict(x):
# posterior is proportional to prior times likelihood; compare in log space for stability
scores = {c: np.log(s["prior"]) + log_likelihood(x, s["mean"], s["var"]) for c, s in stats.items()}
return max(scores, key=scores.get)
Run it once unchanged, inspect the output, and then alter one input or parameter. The compact implementation is designed for learning; use the tested library workflow below for real projects.
Practical tutorial
Build Naive Bayes with scikit-learn
GaussianNB is a fast probabilistic baseline for continuous features with class-specific Gaussian likelihoods.
JupyterLab, Google Colab, or VS Code
Create an isolated virtual environment for a local project, or paste the cells into a hosted notebook. Pin package versions before deploying a reproducible application.
python -m pip install scikit-learn
- Prepare the data.Numeric or categorical features and class labels. Validate its shape, type, range, and ordering before training or execution.
- Configure the algorithm.Begin with explicit, conservative parameters and a fixed random seed whenever the library supports one.
- Fit or execute.Calculate posterior probability from prior and likelihood.
- Inspect the result.A probability distribution over classes. Then apply the evaluation checks in the next section.
from sklearn.datasets import load_wine
from sklearn.metrics import classification_report, log_loss
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=42
)
model = GaussianNB(var_smoothing=1e-9).fit(X_train, y_train)
probability = model.predict_proba(X_test)
print(classification_report(y_test, model.predict(X_test)))
print("log loss:", log_loss(y_test, probability))
API details and version-specific options: official scikit-learn reference →
Evaluation
How to evaluate the result
A successful run is not enough. Evaluate the output against the intended use, compare it with a simple baseline, and preserve a genuinely unseen test case whenever the task involves learned parameters.
- Use log loss to assess probability quality in addition to classification accuracy.
- Inspect feature distributions within each class to judge the Gaussian assumption.
Record the data version, package versions, parameters, random seeds, and evaluation procedure. Re-run the same workflow before publishing a benchmark or deploying a model.
Common mistakes
Pitfalls and how to avoid them
These failure modes are common in tutorials and production systems. Treat them as review questions, not just after-the-fact debugging advice.
- Strongly dependent features can make posterior probabilities overconfident.
- Use MultinomialNB or BernoulliNB instead for count or binary features.
- Tiny class samples produce unreliable likelihood estimates.
Project checklist
Before using Naive Bayes in a project
- Define the prediction or discovery objective before selecting the algorithm.
- Split data before fitting preprocessing and tune only inside cross-validation.
- Record data versions, random seeds, features, hyperparameters, and evaluation metrics.
- Compare against a simple baseline and inspect errors by meaningful subgroups.
- Monitor input drift and real-world performance after deployment.
Further reading
Official documentation and next steps
Use the official documentation to confirm supported parameters, current defaults, input requirements, and version changes.
This guide is an educational introduction, not a substitute for domain validation. For consequential applications, review the source documentation, test against representative data, and involve a subject-matter expert.
Learn by doing
See Naive Bayes in motion
Open the interactive lesson to adjust parameters, scrub through the process, replay the animation, and compare the explanation with the Python code.