Email Classification and Personal AI: Rules, Naive Bayes, Transformers, Specialists, and Evaluation
On this page39
A from-zero visual tutorial building email classification from rules and Naive Bayes through personalization, specialist-model cascades, confidence, local model evaluation, and safe promotion.
Article details
- Status
- Building Publicly
- Subcategory
- Thunderbird AI
- Last reviewed
- 3 Sept 2026
- Prerequisites
- No probability, machine-learning, or transformer knowledge required
Suspicious sign-in blocked — verify your account
A predicted category is routing metadata. It may help organize or retrieve an email, but it is not evidence that a factual claim inside the email is true.
1. First define the question
Single-label classification
finance | jobs | security | personal
Multi-label classification
receipt = yes
needs-reply = yes
urgent = no
Binary, ordinal, and extraction tasks
action-required calendar developer-update
finance job-hunt jobs
legal newsletter personal
promotion security shipping
social-update support travel
2. Classification is a pipeline, not one mysterious function
decoded fields → representation → scores → confidence → precedence → routing label
3. Rules: the baseline that refuses to be embarrassed
if (/\b(password|login|verification)\b/i.test(message)) {
return { category: "security", confidence: "high" };
}
if (/\b(invoice|receipt|payment|bank)\b/i.test(message)) {
return { category: "finance", confidence: "high" };
}
Precision and recall already appear at the rule stage
4. Learning begins with labelled examples
{
label: "finance",
subject: "Card transaction",
author: "alerts@example.test",
text: "card transaction merchant debited"
}
Training, validation, and testing answer different questions
5. Tokenization: turning a string into countable units
This browser implementation mirrors the source contract used by the generated fixture. Change the text to see which evidence survives before the model sees it.
6. Bag of words: a document becomes a sparse vector
[invoice, payment, receipt, interview, recruiter, vacancy]
invoice payment receipt interview recruiter vacancy
1 1 1 0 0 0
7. Probability from scratch: count possible worlds
Class prior
Before seeing any words, finance receives a 30% starting share under this training distribution.
Token likelihood before smoothing
The vertical bar means “given.” Read this as probability of invoice, given that the class is finance.
Bayes' rule
Evidence updates the starting prior. P(words) is shared by every candidate class, so ranking can ignore it.
Multinomial Naive Bayes decision
Start with the class prior, multiply the likelihood of every observed token, and select the largest result.
8. A complete Naive Bayes dry run
finance → "invoice payment receipt"
jobs → "interview recruiter vacancy"
Add-one smoothed likelihood
The numerator gives this word one extra observation; the denominator accounts for one extra observation for every vocabulary entry.
Finance score
Both observed words occurred in the finance training document.
Jobs score
Smoothing keeps jobs possible, but each unseen word contributes a smaller likelihood.
Query:
9. Why real implementations add logarithms
Product-to-sum identity
A product of tiny positive values becomes a sum of manageable negative values.
Stable log score
The ordering is unchanged because logarithm is monotonic: if A is larger than B, log(A) is larger than log(B).
10. Build and run the real sparse classifier
for (const example of trainingExamples) {
const tokens = tokenize(subject + "\n" + author + "\n" + body);
classExampleCount[label] += 1;
for (const token of tokens) {
vocabulary.add(token);
tokenCount[label][token] += 1;
classTokenTotal[label] += 1;
}
}
score[label] = log(classExampleCount[label] / allExampleCount);
for (const token of tokenize(newMessage)) {
const numerator = (tokenCount[label][token] ?? 0) + 1;
const denominator = classTokenTotal[label] + vocabulary.size;
score[label] += log(numerator / denominator);
}
11. Priors, imbalance, and shortcuts
12. Why a transformer sees more than counts
The bank approved my card dispute.
We sat on the river bank after lunch.
premise: A recruiter scheduled your engineering interview.
hypothesis: This email is about jobs.
Context is created, not looked up
Fine-tuning and zero-shot NLI solve the mapping differently
13. The label list is part of the input
14. An actual local ModernBERT experiment
tasksource/ModernBERT-base-nli
revision de4ab7e77845098b7fab7f6ab9d370ddff27b19c
role: modernbert-intent
hypothesis: "This email is about {}."
execution: local CPU runner
Fixture schema:
15. Confidence is a decision problem
16. Combine methods with an explicit cascade
1. user-approved template override
2. exact deterministic rule
3. sufficiently confident user-trained sparse model
4. configured transformer hint
5. safe fallback
17. Evaluate what fails, not only what wins
Precision
Of everything routed into this class, how much belonged there?
Recall
Of everything that belonged in this class, how much did we find?
F1 score
The harmonic mean becomes small when either precision or recall is small.
18. A failure gallery is part of the model
19. Seven experiments that turn the tutorial into evidence
A practical build order for a new classifier
20. What Thunderbird taught us
A classifier does not discover the one true category hidden inside an email. We define a question, construct a representation, learn or encode a decision rule, and choose how much uncertainty the product may act on.
21. Personalization and learning from corrections
Mail from this sender is finance.
This subject shape is a receipt.
Messages like these belong in jobs.
Do not summarize this field externally.
This group should be called Project Atlas.
| Level | Stored object | Best use | Main risk |
|---|---|---|---|
| Preference | Explicit setting | Stable user choice | Too coarse |
| Rule | Condition → action or label | Exact known pattern | Brittle wording |
| Template | Repeated structure plus slots | Machine-generated mail | Format drift |
| Small local classifier | Examples and token statistics | Flexible categories | Overfitting |
| Fine-tuned model | Updated neural parameters | Repeated contextual task | Cost, privacy and rollback |
22. One correction can spread several distances
23. Watch a tiny personalization curve
24. Overfitting, active learning and shadow mode
Prediction entropy
Entropy rises when probability spreads across labels. Combine uncertainty with diversity and user value so strange outliers do not consume every request.
25. Specialist models and conditional compute
| Role | Input | Output | Useful objective |
|---|---|---|---|
| Classifier | Message | Closed label | Cross-entropy and calibration |
| NER model | Tokens plus requested types | Typed spans | Span precision and recall |
| Embedder | Text | Fixed-width vector | Contrastive similarity |
| Reranker | Query and candidate | Relevance score | Pairwise or listwise ranking |
| Summarizer | Long source | Shorter text | Factual coverage and faithfulness |
| Generator | Instructions and evidence | New answer or draft | Task pass and grounded generation |
26. A cascade pays expensive costs conditionally
Expected cascade cost
Later cost is paid only for inputs reaching that stage. A confidently wrong early result can also block the specialist that was needed.
27. Evaluation, model selection and promotion
input bounded fictional source cards and one question
output concise answer plus required source URI
must preserve identifiers and amounts
must not invent missing facts or cite an absent source
budget at most 1,024 completion tokens
Corpus identity
Without the digest, a later report cannot prove that it evaluated the same test.
28. Quantization and output budgets change the product
Idealized raw weight memory
Runtime memory also includes scales, caches, activations, buffers and framework overhead.
29. Read a recorded local-model comparison
In the dated Thunderbird reproducibility run, the 8B candidate alone passed all six expanded fictional source-fact cases at a 1,024-token cap. The larger 27B candidate was slower and missed the complex comparison after exhausting its budget.
30. Quality gates and the Pareto frontier
31. Promotion and rollback are part of evaluation
Personalization chooses how far a correction should spread. Specialist routing chooses which computation should run. Evaluation proves whether the complete, reproducibly identified configuration deserves to replace the current one.
Primary references
- Stanford IR Book: Naive Bayes text classification
- Guo et al.: On Calibration of Modern Neural Networks
- scikit-learn: Classification probability calibration
- ModernBERT: Smarter, Better, Faster, Longer
- tasksource/ModernBERT-base-nli model card
- Settles: Active Learning Literature Survey
- LoRA: Low-Rank Adaptation of Large Language Models
- GLiNER: Generalist Model for Named Entity Recognition
- T5: Exploring the Limits of Transfer Learning
- MLPerf Inference benchmark rules and results
- NIST AI Risk Management Framework
- Qwen3 model source and documentation