Naive Bayes under sparse data
Naive Bayes turns sparse counts into additive evidence—quickly, smoothly, and with assumptions in plain sight.
Support tickets need explainable routing under a 15 ms latency budget.
This chapter moves from count class evidence to audit sparse failures. We will make the idea concrete in a small code example before placing it back inside a production system with 15 ms batch-one latency.
Inspect influential tokens, unknown-token behavior, calibration, language slices, and preprocessing parity.
Verify the behavior illustrated in multinomial_nb.py, then measure decision utility, slice reliability, and system latency.
Unscaled revenue dominates kNN distance while perfectly separating features destabilize unregularized logistic coefficients. An unsafe release must degrade to a named baseline or the last known-good version.
Build the idea one layer at a time.
Naive Bayes makes a deliberately strong independence assumption and turns it into a remarkably effective sparse-data baseline.
For text, multinomial Naive Bayes combines a class prior with token likelihoods, pretending tokens are conditionally independent given the class. The assumption is rarely literally true, but the resulting evidence accumulator can work well with few examples and huge vocabularies.
Use Laplace smoothing so an unseen class-token pair does not force the whole probability to zero, and add log probabilities to avoid numeric underflow. The model is fast and interpretable, though its raw probabilities are often overconfident.
- Bayes rule
- feature scaling
- distance concentration
- hinge loss
Follow the reasoning before touching the code.
- 01
Count class evidence
From training only, count labels and token occurrences per label under a fixed vocabulary and tokenizer.
- 02
Smooth and add logs
Add a pseudocount to every vocabulary term and sum log-likelihoods with the log prior.
- 03
Audit sparse failures
Inspect influential tokens, unknown-token behavior, calibration, language slices, and preprocessing parity.
from math import log
vocabulary = ["refund", "urgent", "thanks", "question"]
counts = {
"urgent": {"refund": 4, "urgent": 5, "thanks": 0, "question": 1},
"routine": {"refund": 1, "urgent": 0, "thanks": 4, "question": 5},
}
priors = {"urgent": 0.4, "routine": 0.6}
document = ["refund", "urgent"]
def score(label):
total = sum(counts[label].values()) + len(vocabulary)
evidence = sum(log((counts[label][token] + 1) / total) for token in document)
return log(priors[label]) + evidence
scores = {label: score(label) for label in counts}
print(scores, "prediction", max(scores, key=scores.get))Score a short ticket with smoothed token likelihoods.
What to notice
- The zero urgent-token count for routine remains finite because smoothing contributes one pseudocount.
- The class prior matters, but repeated token evidence can outweigh it in log space.
YOUR TURN Pause and predict before revealing the answer.
Why should a production tokenizer ignore or explicitly bucket a token outside vocabulary instead of indexing it directly here?
Need a hint?
The count dictionaries and smoothing denominator define probabilities only for the fixed vocabulary.
Check your reasoning
An unknown token has no learned count or declared probability; use a versioned unknown-token policy so training and serving handle it identically.
Lessons 1, 2 in this course.
Connect the chapter to the course’s quantitative spine.
Naive Bayes turns sparse counts into additive evidence—quickly, smoothly, and with assumptions in plain sight. The logistic probability below is the shared course-level lens that helps quantify the surrounding system. Name each symbol, check its units or shape, and use only values that were available at the production cutoff.
Logistic probability
| Symbol | Meaning / shape / unit |
|---|---|
x | feature vector |
β | learned coefficients |
xᵀβ | linear log-odds score |
Open derivation and numerical substitution
Start from the production quantity being optimized, substitute the observed values with their declared units, then isolate the model-controlled term. Preserve shape annotations at each step so broadcasting or aggregation cannot silently change the result.
- Write the named inputs: x, β, xᵀβ.
- Substitute one small, hand-checkable batch before vectorizing.
- Calculate an independent reference value and compare within a declared tolerance.
# equation → code contract
inputs = validate_shapes_and_units(batch)
value = compute_c04(inputs)
assert is_finite(value)Change one assumption and make the tradeoff visible.
Use the worked chapter as your prediction, then change one input in the lab and explain why the output moves. The lab runs predefined TypeScript and never executes learner code, so the focus stays on the concept rather than setup.
Regularization boundary lab
Increase regularization and watch complexity trade against margin violations.
Assumption: Synthetic standardized two-feature classification problem.
Open nonvisual data table
| Item | Computed state | Interpretation |
|---|---|---|
| x=-2 | logit -2.57 | negative |
| x=-1 | logit -1.29 | negative |
| x=0 | logit 0.00 | negative |
| x=1 | logit 1.29 | positive |
| x=2 | logit 2.57 | positive |
Trace the complete operating path.
Carry the chapter’s central idea into the system: Naive Bayes turns sparse counts into additive evidence—quickly, smoothly, and with assumptions in plain sight. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.
- 01
Turn “Count class evidence” into a written invariant and a failing test.
- 02
Promote multinomial_nb.py from illustration to a versioned implementation with representative fixtures.
- 03
Use “Audit sparse failures” as the release checkpoint: Inspect influential tokens, unknown-token behavior, calibration, language slices, and preprocessing parity.
- 04
Serve or materialize behind explicit 15 ms batch-one latency.
- 05
Join telemetry to mature outcomes and retain a rollback path.
Observability
Join service health, input quality, prediction distributions, slice behavior, and mature outcomes by exact version.
Cost
Measure storage, preprocessing, compute, queueing, and human review under a representative arrival pattern.
Failure modes
Unscaled revenue dominates kNN distance while perfectly separating features destabilize unregularized logistic coefficients. Add a detector, owner, mitigation, and stop condition for this class of failure.
Alternatives
Compare a rule, a simpler statistical baseline, and a different system boundary before adding model complexity.
Explain the contract, not just the vocabulary.
Explainable ticket-routing baseline
Compare linear/logistic regression, Naive Bayes, kNN, and SVM under one evaluation and serving contract.
- Preprocessing parity
- Model-family comparison
- Calibration and cost policy
- Serialized latency test
Read primary material with a purpose.
Return to the opening failure.
Compare quality, calibration, latency, memory, and interpretability under one stable validation contract.
For this lesson, the release evidence is the worked code example, a hand-checked formal result, deterministic simulation output, a ≥80% checkpoint, the production rubric, and a named fallback. The course resolves when the system can produce a justified baseline across regression, naive bayes, knn, and svm.