Build a Spam Email Classifier with Naive Bayes and Feature Engineering
classical-ml nlp feature-engineering model-evaluation View full code for this problem
ML Problem & Solution
Spam Filtering with Naive Bayes
Catching 94% of spam is easy. Catching it while losing fewer than 1 in 10,000 real emails is the problem.
A regional email provider accepts 2.8 million inbound messages a day for 340,000 mailboxes. Roughly 47% of that volume is spam by the time it clears the SMTP-level checks, which is 1.3 million messages a day that should never reach an inbox. The support queue tells a different story than the volume does: almost nobody files a ticket because they got spam, and every single ticket that does arrive is about a real message that went missing. An invoice. A job offer. A password reset. One of those tickets costs more support time and more customer trust than ten thousand pieces of spam that slipped through.
That asymmetry is the entire problem, and it is why spam filtering is a badly specified task until you attach a number to it. “Classify email as spam or not spam” invites you to optimize accuracy, and accuracy is close to meaningless here: a filter that blocks everything scores 47%, a filter that blocks nothing scores 53%, and both are catastrophic. The real specification is a constrained one. Block as much spam as possible subject to a hard ceiling on the rate at which legitimate mail is blocked, and that ceiling is set by the support economics rather than by anything statistical. Here it is 1 legitimate message in 10,000, a false positive rate of 0.01%.
The naive approach fails in a specific and instructive way. The obvious first filter is a keyword blocklist: match on viagra, lottery, wire transfer, a few hundred more, and block on any hit. On the last 30 days of traffic that catches 61.3% of spam, which sounds like a start, and it blocks 0.41% of legitimate mail, which is 41 times the budget. Worse, it degrades on its own. A blocklist is a public target: spammers can test against it, and within days viagra becomes v1agra, \/iagra, and an image with no text at all. The blocklist has no way to learn that a message mentioning wire transfer from a sender the recipient has corresponded with for three years is a normal message, because it has no notion of evidence accumulating across many weak signals.
The structure worth holding onto is a medical screening test, not a lock. No single symptom identifies a disease, and no single word identifies spam. What a good filter does is accumulate many individually unconvincing signals into a likelihood ratio: this message contains six tokens that are 20 times more common in spam than in real mail, was sent from an autonomous system that sends 94% spam, has a Received chain that does not match its envelope sender, and has no prior correspondence with the recipient. Any one of those is weak. Together they are overwhelming. That accumulation of independent-ish evidence into a posterior odds ratio is precisely what Naive Bayes computes, which is why it remains the right first model for this problem 25 years after it was first applied to it.
Given the raw RFC 5322 source of an inbound message plus the recipient’s correspondence history, predict whether the message is spam, maximizing recall subject to a false positive rate at or below 0.01% on legitimate mail, at under 20 milliseconds per message and with a model that can be fully retrained in minutes.
Framing the Problem
This is binary classification under a hard asymmetric error constraint, on a non-stationary, adversarial input distribution, with per-recipient label noise. Each of those four qualifiers changes a decision downstream, so it is worth stating them precisely rather than treating this as a generic text classification task.
The target is is_spam, and defining it is harder than it looks because there is no ground truth independent of the recipient. We label from three sources with different trust levels.
Spam trap mailboxes. Addresses that have never been published or used to sign up for anything, so every message arriving at them is unsolicited by construction. These are the cleanest positive labels available: 100% precision, roughly 180,000 messages a day, and heavily biased toward bulk campaigns rather than targeted phishing.
User reports. A recipient clicking “report spam” gives a positive label with maybe 96% precision. The 4% is real: people report newsletters they signed up for and forgot, and they report messages from a colleague they are annoyed with. A message with a single report and 400 other recipients who left it alone is not spam.
Non-spam is the hard half. There is no “this is definitely legitimate” button that anyone presses. We infer negatives from engagement: messages that were opened, replied to, moved to a folder, or left in the inbox for more than 14 days without a report. This is a weak negative and it is biased, because it under-samples legitimate mail that nobody engages with, which is exactly the receipts and notifications that a false positive hurts most.
Constraints
- False positive rate at or below 0.01% on legitimate mail. This is the constraint that determines the shape of everything else. It is not a tuning target, it is a ceiling the product cannot exceed.
- Latency budget 20ms p99 per message, at an average of 32 messages a second and a Monday morning peak near 160 a second. The filter sits in the SMTP delivery path, so a slow filter becomes a queue, and a queue becomes delayed mail.
- Retrain in minutes, not hours. The input distribution is adversarial and moves daily. A model that takes six hours to retrain is a model that is always fighting last week’s campaigns. This constraint is what makes Naive Bayes competitive against strictly more accurate alternatives.
- Per-recipient adaptability. A cryptocurrency newsletter is spam to most mailboxes and wanted mail to a few hundred. A single global model cannot express that, so the global score needs a per-recipient adjustment layer.
- Explainability for the quarantine UI. When a message is quarantined, the release page must say why in terms a person understands. Token-level log-odds contributions give this almost free, which is a real operational advantage of a linear-in-log-space model.
Recall at 0.01% FPR, written R@FPR=1e-4. Pick the score threshold that produces exactly one false positive per 10,000 legitimate messages on a held-out set, then report what fraction of spam that threshold catches. This is the right headline number because it matches how the filter is actually operated: the ceiling on lost mail is fixed by the business, and the only free variable is how much spam you catch underneath it. Plain accuracy is useless at a 47% base rate, ROC-AUC is misleading because 99.99% of the ROC curve describes operating points nobody would ever deploy, and F1 silently prices one lost invoice as equal to one delivered spam, which is off by four orders of magnitude.
Guardrail metrics: false positive rate computed separately on transactional mail (receipts, password resets, calendar invites) where a miss is most damaging, false positive rate on first-contact senders, p99 scoring latency, and the rate at which quarantined messages are released by users, which is the closest thing to an online false positive estimate.
Out of scope: the SMTP-layer defenses that run before this model and remove about 71% of raw connection attempts through IP reputation, greylisting, SPF, DKIM, and DMARC checks. Those are cheap, near-zero false positive, and not machine learning. This model operates on what survives them, which is why the base rate here is 47% rather than the 85% often quoted for raw inbound volume.
The hard error constraint changes which model family is appropriate, not just which threshold you pick. At a 0.01% false positive budget you are operating in the extreme tail of the score distribution, where performance is dominated by how well the model handles rare and unseen tokens rather than by how it separates the bulk of the distribution. Two models with identical ROC-AUC can differ by 15 points of recall at that threshold. Always tune, select, and report at the operating point you will actually deploy at.
Data and Features
The training corpus is 4.2 million messages over 18 months, downsampled from the full stream to keep the class ratio at the natural 47% rather than balancing it, because the prior matters and the decision threshold is calibrated against real-world odds.
| Source | Label | Messages | Notes |
|---|---|---|---|
| Spam traps | spam | 1.44M | clean positives, biased to bulk campaigns |
| User reports | spam | 0.53M | 96% precision, requires a corroboration rule |
| Engaged mail | ham | 1.71M | opened, replied, or foldered |
| Aged inbox mail | ham | 0.52M | 14 days in inbox, no report, no engagement |
Tokenization is a feature engineering decision, not a preprocessing step
The single largest accuracy differences on this problem come from the tokenizer, not the model. Spam is written by people actively trying to defeat tokenizers, so the choices below are all responses to specific evasions we observed in the corpus.
# Spam-aware tokenizer. Every rule here exists because of a specific evasion
# seen in the corpus, noted inline. Order matters: normalize before splitting.
import re
import unicodedata
HOMOGLYPHS = str.maketrans({
"а": "a", "е": "e", "о": "o", "р": "p",
"с": "c", "у": "y", "х": "x", "і": "i",
"․": ".", "ı": "i",
})
TOKEN_RE = re.compile(r"[a-z0-9$!£€.\-'&/]{1,24}", re.IGNORECASE)
URL_RE = re.compile(r"https?://([^/\s]+)", re.IGNORECASE)
def normalize(text: str) -> str:
# Cyrillic and lookalike substitution is the most common single evasion:
# a Cyrillic small 'a' renders identically and defeats exact matching.
text = unicodedata.normalize("NFKC", text)
return text.translate(HOMOGLYPHS).lower()
def tokenize(subject: str, body: str, html: str) -> list[str]:
tokens: list[str] = []
# Subject tokens get their own namespace. The same word carries very
# different evidence in a subject line than in body text.
for tok in TOKEN_RE.findall(normalize(subject)):
tokens.append("subj:" + tok)
body_norm = normalize(body)
for tok in TOKEN_RE.findall(body_norm):
# Keep punctuation-bearing tokens intact. '$1,000' and 'FREE!!!' are
# strong signals that a word-character-only tokenizer destroys.
tokens.append(tok)
# URL hostnames and their registrable domains are separate features. The
# full host churns per campaign; the registrable domain persists longer.
for host in URL_RE.findall(html or body_norm):
host = normalize(host)
tokens.append("url:" + host)
parts = host.split(".")
if len(parts) >= 2:
tokens.append("dom:" + ".".join(parts[-2:]))
tokens.append("tld:" + parts[-1])
return tokens
Four choices in there are load-bearing, and each was worth more than any hyperparameter we later tuned.
Namespacing by message part. The token invoice in a subject line and in body text are different features. Splitting them added 2.1 points of recall at the operating point, because subject lines are short, deliberate, and much less diluted than bodies.
Keeping punctuation inside tokens. free is a mildly spammy word that appears in plenty of legitimate mail. free!!! appears almost nowhere else. A tokenizer that strips non-word characters collapses both into free and throws away the more discriminative of the two. Paul Graham made exactly this point in Better Bayesian Filtering in 2003 and it is still true.
Homoglyph normalization before tokenizing. Without it, each Cyrillic variant of a spam word is a distinct unseen token and the model has no evidence about it. This is a pure evasion countermeasure and it is worth 3.4 points.
Domain, host, and TLD as three separate features. Campaign hostnames rotate daily and are nearly useless as learned features, but their registrable domain survives longer and their TLD survives indefinitely: several newer TLDs run above 90% spam in this corpus while .gov and .edu run near zero.
The header features that carry the load
Token features do most of the work but the header block is where the cheapest, most durable signal lives, because it describes the sending infrastructure rather than the content, and infrastructure is more expensive for an adversary to change than words are.
# Structural and reputation features from the envelope and headers. These are
# cheap, hard to evade, and carry most of the signal on image-only spam where
# there are almost no tokens to score.
from dataclasses import dataclass, asdict
@dataclass
class HeaderFeatures:
spf_result: str # pass, fail, softfail, neutral, none
dkim_valid: bool
dmarc_aligned: bool
received_hop_count: int
envelope_matches_from: bool
reply_to_differs_from: bool
sender_asn: str
sender_tld: str
has_list_unsubscribe: bool
html_to_text_ratio: float
image_only: bool
attachment_ext: str
subject_is_all_caps: bool
subject_non_ascii_ratio: float
prior_inbound_from_domain: int # recipient-specific correspondence count
prior_outbound_to_domain: int
domain_age_days: int
def header_features(msg, recipient_history) -> dict:
envelope_from = msg.envelope_from.split("@")[-1].lower()
header_from = msg.header_from.split("@")[-1].lower()
return asdict(HeaderFeatures(
spf_result=msg.auth["spf"],
dkim_valid=msg.auth["dkim"] == "pass",
dmarc_aligned=msg.auth["dmarc"] == "pass",
received_hop_count=len(msg.received_chain),
envelope_matches_from=(envelope_from == header_from),
# A Reply-To pointing somewhere other than From is the single most
# discriminative header feature for phishing in this corpus.
reply_to_differs_from=bool(
msg.reply_to and msg.reply_to.split("@")[-1].lower() != header_from),
sender_asn=msg.connecting_asn,
sender_tld=header_from.rsplit(".", 1)[-1],
has_list_unsubscribe="list-unsubscribe" in msg.headers,
html_to_text_ratio=msg.html_bytes / max(msg.text_bytes, 1),
image_only=(msg.text_bytes < 40 and msg.image_count > 0),
attachment_ext=(msg.attachments[0].ext if msg.attachments else "none"),
subject_is_all_caps=msg.subject.isupper() and len(msg.subject) > 8,
subject_non_ascii_ratio=msg.subject_non_ascii / max(len(msg.subject), 1),
prior_inbound_from_domain=recipient_history.inbound_from(header_from),
prior_outbound_to_domain=recipient_history.outbound_to(header_from),
domain_age_days=msg.sender_domain_age_days,
))
prior_outbound_to_domain deserves special attention because it is the feature that protects the false positive budget. If the recipient has ever sent mail to this domain, the odds that an inbound message from it is spam drop by a factor of roughly 180. Almost all of our remaining false positives are first-contact senders, and this feature is why.
Building features from headers that the receiving infrastructure adds after the spam verdict has already been made. The X-Spam-Status, X-Quarantine-ID, and delivery-folder headers written by the current production filter are present in the stored corpus and absent at scoring time. A model that picks them up reaches 99.7% recall in offline evaluation and roughly the current filter's performance in production, because it learned to read the old filter's answer. Maintain an explicit allowlist of headers the model may see, asserted against the set available at SMTP time, rather than a blocklist of ones it may not.
Leakage specific to this problem
Beyond the verdict-header trap, two more forms of contamination are near-universal on spam corpora.
Campaign duplication across the split. A single spam campaign sends 40,000 near-identical messages over six hours. Split randomly and the same campaign appears in both train and test, so the model gets credit for memorizing a template it will never see again. Measured cost of getting this wrong: reported recall at the operating point comes out 11.3 points too high.
Temporal leakage through the adversary. Spam from March tells you about spam in April but the relationship runs one way. Training on a random sample that includes future messages lets the model see campaigns that had not launched yet, which is precisely the advantage it will never have in production.
# Time-ordered split with campaign de-duplication. Both are required: either
# one alone still leaks. The SimHash groups near-duplicate bodies so an entire
# campaign lands on one side of the split.
import numpy as np
import pandas as pd
from simhash import Simhash
def campaign_key(tokens: list[str]) -> int:
# 64-bit SimHash over the token multiset, truncated to 52 bits so that
# messages differing only in a personalization field collide.
return Simhash(tokens).value >> 12
def time_split(frame: pd.DataFrame, valid_days: int = 14,
test_days: int = 14, embargo_days: int = 2):
frame = frame.sort_values("received_at").reset_index(drop=True)
frame["campaign"] = frame["tokens"].map(campaign_key)
last = frame["received_at"].max()
test_start = last - pd.Timedelta(days=test_days)
valid_start = test_start - pd.Timedelta(days=valid_days)
# Embargo: campaigns straddling a boundary are dropped rather than assigned,
# which is cleaner than trying to decide which side owns them.
train_end = valid_start - pd.Timedelta(days=embargo_days)
train = frame[frame["received_at"] < train_end]
valid = frame[(frame["received_at"] >= valid_start)
& (frame["received_at"] < test_start)]
test = frame[frame["received_at"] >= test_start]
seen = set(train["campaign"])
valid = valid[~valid["campaign"].isin(seen)]
seen |= set(valid["campaign"])
test = test[~test["campaign"].isin(seen)]
return train, valid, test
The Naive Baseline
Three baselines, measured on the same held-out 14 day window: 412,000 messages, 193,000 of them spam, 219,000 legitimate.
# Baseline 1: majority class. Baseline 2: the keyword blocklist that this
# filter replaces, which is still what a lot of small mail servers run.
# Baseline 3: out-of-the-box multinomial Naive Bayes on word counts, which is
# the "just use sklearn" answer and the one worth beating properly.
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
BLOCKLIST = {
"viagra", "cialis", "lottery", "winner", "inheritance", "nigerian",
"unsubscribe", "casino", "rolex", "replica", "enlargement", "wire",
"bitcoin", "crypto", "loan", "mortgage", "refinance", "pharmacy",
}
def majority_class(n: int) -> np.ndarray:
# The 47% base rate means this scores 53% accuracy and 0% recall.
return np.zeros(n, dtype=np.int8)
def blocklist_predict(bodies: list[str]) -> np.ndarray:
# Binary and unthresholdable: there is no knob to trade recall for FPR.
return np.array([
int(bool(BLOCKLIST & set(normalize(b).split()))) for b in bodies
], dtype=np.int8)
def vanilla_nb(train_text, train_y, test_text):
# The default recipe: word counts, alpha=1.0, no header features,
# no binarization, no calibration.
vec = CountVectorizer(lowercase=True, min_df=2)
x_train = vec.fit_transform(train_text)
model = MultinomialNB(alpha=1.0).fit(x_train, train_y)
return model.predict_proba(vec.transform(test_text))[:, 1]
Results at the operating point, where the threshold for each scoreable model is chosen on the validation window to hit exactly 0.01% FPR:
| Baseline | Accuracy | Recall @ FPR 1e-4 | Actual FPR | PR-AUC |
|---|---|---|---|---|
| Majority class (all ham) | 53.2% | 0.0% | 0.00% | 0.469 |
| Keyword blocklist | 76.4% | not tunable | 0.41% | not defined |
| Vanilla multinomial NB | 96.1% | 71.8% | 0.010% | 0.982 |
Read those three rows carefully, because each fails in a different way and the differences drive the rest of the post.
The majority class baseline is not a joke entry. It sets the floor that “96% accuracy” has to be judged against, and 96% accuracy against a 53% floor is a much less impressive number than it sounds.
The blocklist cannot be moved to the operating point at all. It produces a binary verdict with no score, so there is no threshold to turn and no way to trade recall for a lower false positive rate. Its 0.41% FPR is 41 times the budget, and the only available fixes are removing keywords, each of which costs recall in large discrete jumps. This inability to tune is a structural defect, not a tuning failure.
Vanilla Naive Bayes is the interesting one. Its accuracy of 96.1% looks like a solved problem, and its recall at the actual operating point is 71.8%, which means it is missing more than a quarter of spam once the false positive constraint is enforced. The gap between “96% accurate” and “misses 28% of spam” is the entire reason this post has more sections. Three things are wrong with it: it scores raw word counts, so a spam message that repeats bitcoin 40 times gets 40 independent votes from a single piece of evidence; it sees no header or reputation features at all, so image-only spam with six tokens is invisible to it; and its output probabilities are so badly calibrated that choosing a threshold from them is nearly arbitrary.
The Solution
Fit a binarized multinomial Naive Bayes model over a hashed union of token and header features, with isotonic calibration and a threshold selected directly at the false positive budget. The pieces matter in that order: binarization is worth the most, header features next, calibration is worth nothing in recall and is what makes the threshold meaningful and stable across retrains.
How Naive Bayes accumulates evidence
The model computes posterior log-odds as a prior plus a sum of per-feature log-likelihood ratios:
log P(spam | x)/P(ham | x)
= log P(spam)/P(ham) + sum over features f in x of log P(f | spam)/P(f | ham)
Every feature contributes an additive vote in log-odds space, and the vote for feature f is just how much more often f shows up in spam than in ham. That is the screening-test analogy made literal: each symptom multiplies the odds, and multiplying odds is adding log-odds.
The “naive” part is the assumption that features are conditionally independent given the class, which for email text is flatly false. wire and transfer co-occur constantly, so a message containing both gets counted as two independent pieces of evidence when it is closer to one. This is why the model’s probability estimates are unusable even though its ranking is good, and it is the single most important practical fact about Naive Bayes.
Binarization is the highest-leverage change
The conditional independence violation gets much worse with repetition. Under a multinomial model, a token appearing 40 times contributes 40 times its log-likelihood ratio, which treats 40 occurrences as 40 independent draws. They are not: they are one authorial decision. The fix is to score presence rather than frequency, which is the Bernoulli-style event model applied to a multinomial estimator, sometimes called binarized or boolean multinomial Naive Bayes. It is worth 9.2 points of recall at the operating point here, more than any other single change.
# The solution model. Binarized multinomial NB over hashed token + header
# features, fit with sparse counts and scored as log-odds.
import numpy as np
import scipy.sparse as sp
from sklearn.feature_extraction import FeatureHasher
from sklearn.naive_bayes import MultinomialNB
N_FEATURES = 2 ** 20 # 1.05M columns; collision rate under 0.4% at 340k vocab
ALPHA = 0.08 # tuned on the validation window, see below
def featurize(messages, histories) -> sp.csr_matrix:
"""Hash tokens and header features into one binary sparse matrix."""
hasher = FeatureHasher(n_features=N_FEATURES, input_type="dict",
alternate_sign=False)
rows = []
for msg, hist in zip(messages, histories):
# Set, not list: this is the binarization. One vote per distinct
# feature, regardless of how many times it appears in the message.
feats = {tok: 1.0 for tok in set(tokenize(msg.subject, msg.text,
msg.html))}
for name, value in header_features(msg, hist).items():
if isinstance(value, bool):
feats[f"h:{name}={int(value)}"] = 1.0
elif isinstance(value, str):
feats[f"h:{name}={value}"] = 1.0
else:
# Bucket numerics into log-spaced bins. NB needs categorical
# features, and log bins match how these quantities behave.
bucket = int(np.floor(np.log1p(max(float(value), 0.0)) * 2))
feats[f"h:{name}~{bucket}"] = 1.0
rows.append(feats)
return hasher.transform(rows)
def train_binarized_nb(x_train: sp.csr_matrix, y_train: np.ndarray,
alpha: float = ALPHA) -> MultinomialNB:
model = MultinomialNB(alpha=alpha, fit_prior=True)
model.fit(x_train, y_train)
return model
def score_log_odds(model: MultinomialNB, x: sp.csr_matrix) -> np.ndarray:
"""Raw log-odds. Deliberately not predict_proba: see the calibration note.
joint_log_likelihood already includes the class log-prior, so the
difference of the two columns is the full posterior log-odds.
"""
jll = model._joint_log_likelihood(x)
return jll[:, 1] - jll[:, 0]
Smoothing controls the tail, which is where the operating point lives
The alpha smoothing parameter matters far more here than it does on a balanced, generously thresholded problem, because at a 0.01% false positive rate the threshold sits out where a handful of rare tokens decide individual messages.
A token seen 3 times in spam and 0 times in ham has an unsmoothed log-likelihood ratio of infinity, which lets three observations override every other feature in the message. That is how a legitimate message gets blocked: it happens to contain one rare token that appeared only in spam in the training window. Laplace smoothing at alpha = 1.0 overcorrects in the other direction, flattening the genuinely discriminative rare tokens that carry most of the signal on short messages.
# Selecting alpha at the operating point rather than by accuracy or AUC.
# The curve is flat in accuracy and strongly peaked in R@FPR=1e-4, which is
# the whole argument for tuning at the deployment threshold.
def select_alpha(x_train, y_train, x_valid, y_valid,
grid=(0.005, 0.02, 0.05, 0.08, 0.15, 0.3, 1.0)) -> float:
best_alpha, best_recall = None, -1.0
for alpha in grid:
model = train_binarized_nb(x_train, y_train, alpha=alpha)
scores = score_log_odds(model, x_valid)
recall = recall_at_fpr(y_valid, scores, target_fpr=1e-4)
if recall > best_recall:
best_alpha, best_recall = alpha, recall
return best_alpha
Measured on the validation window: alpha = 1.0 gives 86.3% recall at the operating point, alpha = 0.08 gives 94.1%, and alpha = 0.005 gives 89.7% as the unsmoothed tail starts producing false positives again. Accuracy varies by less than 0.4 points across that entire range, which is why tuning on accuracy finds nothing.
Calibration does not improve ranking, and you still need it
Naive Bayes probabilities are pathologically overconfident: because correlated features are counted as independent evidence, the log-odds pile up and predict_proba returns values like 0.99999994 for a large fraction of messages. Zadrozny and Elkan documented this in 2001 and it is the reason you cannot pick a threshold of 0.99 and expect it to mean anything.
Isotonic regression fixes it. It is monotone, so it changes no rankings and therefore no recall at any FPR, but it maps scores onto a probability scale that is stable across retrains. Without it, the raw log-odds threshold that hits 0.01% FPR drifts by 20% or more between daily retrains, so every retrain silently changes the operating point.
# Isotonic calibration plus threshold selection at the FPR budget. The
# calibration buys no recall at all; it buys a threshold that means the same
# thing tomorrow as it does today.
import numpy as np
from sklearn.isotonic import IsotonicRegression
def recall_at_fpr(y_true: np.ndarray, scores: np.ndarray,
target_fpr: float = 1e-4) -> float:
ham = scores[y_true == 0]
spam = scores[y_true == 1]
if len(ham) == 0 or len(spam) == 0:
return 0.0
# The threshold is the (1 - target_fpr) quantile of the ham score
# distribution: exactly target_fpr of ham sits above it.
threshold = np.quantile(ham, 1.0 - target_fpr)
return float((spam > threshold).mean())
class CalibratedSpamFilter:
def __init__(self, target_fpr: float = 1e-4):
self.target_fpr = target_fpr
self.model = None
self.iso = None
self.threshold = None
def fit(self, x_train, y_train, x_valid, y_valid, alpha: float = ALPHA):
self.model = train_binarized_nb(x_train, y_train, alpha=alpha)
raw = score_log_odds(self.model, x_valid)
# out_of_bounds='clip' keeps unseen extreme scores inside [0, 1]
# instead of returning NaN at serving time.
self.iso = IsotonicRegression(y_min=0.0, y_max=1.0, increasing=True,
out_of_bounds="clip").fit(raw, y_valid)
probs = self.iso.predict(raw)
self.threshold = float(np.quantile(probs[y_valid == 0],
1.0 - self.target_fpr))
return self
def predict_proba(self, x) -> np.ndarray:
return self.iso.predict(score_log_odds(self.model, x))
def predict(self, x) -> np.ndarray:
return (self.predict_proba(x) > self.threshold).astype(np.int8)
def explain(self, x_row, feature_names: list[str], top_k: int = 5):
"""Per-feature log-odds contributions for the quarantine release page."""
contrib = (self.model.feature_log_prob_[1]
- self.model.feature_log_prob_[0])
idx = x_row.indices
pairs = sorted(zip(idx, contrib[idx]), key=lambda p: -abs(p[1]))
return [(feature_names[i], round(float(c), 3)) for i, c in pairs[:top_k]]
The per-recipient layer
A global model cannot decide whether a crypto newsletter is spam, because the answer differs by mailbox. The standard fix, and what SpamAssassin’s Bayes plugin has done for two decades, is a second lightweight per-recipient model that adjusts the global score. We keep a per-mailbox token count table updated from that mailbox’s own reports and rescues, and add its log-odds to the global score with a shrinkage weight that grows as the mailbox accumulates labels.
# Per-recipient adjustment. Shrunk toward zero so a mailbox with 3 labels
# barely moves the global score and one with 3,000 can override it.
class RecipientAdjuster:
def __init__(self, shrinkage_k: float = 50.0, max_weight: float = 0.6):
self.shrinkage_k = shrinkage_k
self.max_weight = max_weight
self.tables: dict[str, dict[str, list[int]]] = {}
def update(self, mailbox: str, tokens: set[str], label: int) -> None:
table = self.tables.setdefault(mailbox, {})
for tok in tokens:
counts = table.setdefault(tok, [0, 0])
counts[label] += 1
def adjust(self, mailbox: str, tokens: set[str],
global_log_odds: float) -> float:
table = self.tables.get(mailbox)
if not table:
return global_log_odds
n_labels = sum(sum(c) for c in table.values())
weight = min(self.max_weight,
n_labels / (n_labels + self.shrinkage_k) * self.max_weight)
local = 0.0
for tok in tokens:
spam_n, ham_n = table.get(tok, (0, 0))
if spam_n + ham_n >= 2:
local += np.log((spam_n + 0.5) / (ham_n + 0.5))
return global_log_odds + weight * local
The design decision that mattered most was binarizing the token counts, worth 9.2 points of recall at the operating point against every other change we tried, including adding all 16 header features (7.1 points) and retuning alpha (7.8 points). The reason is that it directly patches the model's broken assumption at the point where it breaks worst. Naive Bayes assumes features are independent draws; word repetition inside one document is the least independent thing in the data. Counting each distinct feature once does not fix conditional independence between different words, but it removes the largest and most systematic violation almost for free.
Evaluation and Metrics
Four numbers, because the constraint structure means no single one describes the filter.
Recall at FPR 1e-4. The headline. Fix the threshold at exactly one false positive per 10,000 legitimate messages, report spam caught. Anything that does not hold the false positive rate fixed is not comparable.
Partial ROC-AUC restricted to FPR in [0, 1e-3]. ROC-AUC over the full range is close to useless here: two models can differ by 15 points of recall at the operating point and by 0.002 in full AUC, because 99.9% of the curve’s area describes thresholds that would block thousands of real messages. Standardized partial AUC over the region we actually operate in is the version worth tracking.
FPR by mail category. A single global false positive rate averages over categories with wildly different costs. Transactional mail (receipts, password resets, two-factor codes) is roughly 14% of legitimate volume and generates about 70% of support tickets when blocked, because a delayed newsletter is invisible and a delayed password reset locks someone out.
Quarantine release rate. The share of quarantined messages that a user goes and rescues, which is the only online estimate of false positives available without waiting for a support ticket. It runs about 0.8% of quarantine volume and is the fastest signal for a regression.
# Full spam-filter eval. Reports recall at the FPR budget, partial AUC in the
# low-FPR region, and per-category FPR, because a global FPR hides the
# categories where a false positive actually costs something.
import numpy as np
import pandas as pd
from sklearn.metrics import roc_auc_score, average_precision_score
def partial_auc(y_true, scores, max_fpr: float = 1e-3) -> float:
# McClish-standardized partial AUC: rescaled so 0.5 is random and 1.0 is
# perfect within the FPR region of interest.
return float(roc_auc_score(y_true, scores, max_fpr=max_fpr))
def fpr_by_category(y_true, scores, categories, threshold) -> pd.DataFrame:
frame = pd.DataFrame({"y": y_true, "s": scores, "cat": categories})
ham = frame[frame["y"] == 0]
out = ham.groupby("cat").agg(
messages=("s", "size"),
false_positives=("s", lambda s: int((s > threshold).sum())),
)
out["fpr"] = out["false_positives"] / out["messages"]
return out.sort_values("fpr", ascending=False)
def evaluate_filter(y_true, scores, categories, target_fpr: float = 1e-4) -> dict:
y_true = np.asarray(y_true)
scores = np.asarray(scores, dtype=np.float64)
ham = scores[y_true == 0]
threshold = float(np.quantile(ham, 1.0 - target_fpr))
predicted = scores > threshold
tp = int((predicted & (y_true == 1)).sum())
fp = int((predicted & (y_true == 0)).sum())
return {
"threshold": threshold,
"recall_at_budget": float((scores[y_true == 1] > threshold).mean()),
"precision_at_budget": tp / max(tp + fp, 1),
"realized_fpr": fp / max(int((y_true == 0).sum()), 1),
"partial_auc_1e3": partial_auc(y_true, scores, max_fpr=1e-3),
"pr_auc": float(average_precision_score(y_true, scores)),
"roc_auc_full": float(roc_auc_score(y_true, scores)),
"fpr_by_category": fpr_by_category(y_true, scores, categories, threshold),
}
Held-out 14 day window, 412,000 messages, 193,000 spam, 219,000 ham, all thresholds set on the preceding validation window and never on the test window:
| Metric | Blocklist | Vanilla NB | Binarized NB | Binarized NB + headers | + calibration + recipient |
|---|---|---|---|---|---|
| Recall @ FPR 1e-4 | n/a | 71.8% | 81.0% | 92.4% | 94.1% |
| Precision @ budget | 21.4% | 99.99% | 99.99% | 99.99% | 99.99% |
| Partial AUC (FPR < 1e-3) | n/a | 0.781 | 0.844 | 0.921 | 0.938 |
| PR-AUC | n/a | 0.982 | 0.991 | 0.996 | 0.997 |
| Full ROC-AUC | n/a | 0.9913 | 0.9948 | 0.9981 | 0.9986 |
| FPR, transactional mail | 0.62% | 0.041% | 0.028% | 0.009% | 0.004% |
| Accuracy | 76.4% | 96.1% | 97.2% | 98.8% | 99.1% |
| Retrain wall clock | n/a | 38s | 41s | 54s | 71s |
The two rows to read together are full ROC-AUC and recall at the budget. Vanilla NB posts 0.9913 ROC-AUC, which in most write-ups would be reported as a solved problem, and it catches 71.8% of spam at the threshold we can actually deploy. The final model improves ROC-AUC by 0.0073, a change that would be dismissed as noise in most papers, and it catches 22.3 points more spam. The full-range metric is not wrong so much as it is answering a question nobody asked.
Also note that precision is pinned at 99.99% across every scoreable row, which is what a 0.01% FPR constraint at a 47% base rate mechanically produces. Precision is therefore useless for model selection here. It is a constraint that has been satisfied, not a metric that discriminates.
False positive rate on transactional mail specifically is the number that catches a silent production regression. The global FPR is pinned at the budget by construction, so it cannot move: the threshold is recomputed to hold it. What moves underneath it is the mix, and transactional mail is the most fragile category because receipts and two-factor codes are template-generated, contain money words and urgency language, often come from bulk-sending infrastructure the recipient has never corresponded with, and get almost no engagement even when delivered correctly. A shift in a payment provider's sending infrastructure can take transactional FPR from 0.004% to 0.05% while the global FPR sits at exactly 0.010%, and the first external signal is a support ticket about a missing receipt a week later.
Common Pitfalls and Failure Modes
| Pitfall | Why It Happens | How to Detect | How to Fix |
|---|---|---|---|
| Verdict headers in the feature set | The stored corpus carries X-Spam-* headers written by the current filter, which do not exist at SMTP time |
Offline recall above roughly 99% at the FPR budget, which is not achievable on this data | Allowlist the headers the model may read, asserted against the set available at scoring time |
| Campaign duplication across the split | A 40,000 message campaign gets randomly split across train and test | Recall at budget falls by 10 or more points when the split is redone with SimHash grouping | Time-order the split and group near-duplicate bodies so a campaign lands entirely on one side |
| Tuning on accuracy or full ROC-AUC | Both are flat across the hyperparameters that matter at a 1e-4 threshold | alpha selection shows no signal on accuracy but a 7.8 point spread on recall at budget |
Select every hyperparameter using recall at the deployed FPR budget |
Thresholding on predict_proba |
Naive Bayes is pathologically overconfident, so 0.999 and 0.99999994 are not comparable quantities | A large mass of predicted probabilities at exactly 1.0, and a threshold that drifts between retrains | Threshold on a quantile of the ham score distribution, and isotonically calibrate so the number is stable |
| Raw word counts | 40 occurrences of one token count as 40 independent pieces of evidence | Long messages score far more extremely than short ones with the same content | Binarize: one vote per distinct feature per message |
| Balancing the training classes | Standard advice for imbalance, misapplied to a problem where the prior is real information | Threshold at the budget moves sharply, and the calibration curve tilts | Train on the natural 47% base rate and control the operating point with the threshold |
| Feedback loop poisoning | Quarantined mail is never engaged with, so it becomes training evidence for its own label | A token’s spam probability climbs monotonically across retrains with no new external labels | Hold back a small always-delivered control sample per mailbox to source unbiased ham labels |
| Adversarial evasion via the tokenizer | Homoglyphs, zero-width characters, and image-only bodies defeat exact token matching | Share of messages with fewer than 5 extracted tokens rises; recall drops on that slice | Normalize Unicode before tokenizing, and lean on header features which stay informative at zero tokens |
The single most common mistake on this exact problem is balancing the classes, because "handle the class imbalance" is such reflexive advice that people apply it without checking whether there is a harmful imbalance to handle. At a 47% spam rate there is none, and the class prior is genuine information about the world that Naive Bayes uses correctly through fit_prior=True. Resampling to 50/50 distorts the prior, shifts the whole score distribution, and forces the threshold to move to compensate, which costs 1.4 points of recall at the budget for no benefit. Class balancing is a tool for problems where the positive class is rare enough that the model never learns it. Spam filtering is the opposite: both classes are enormous, and the difficulty lives entirely in the cost asymmetry, which belongs in the threshold and not in the training distribution.
Scaling and Productionizing
The filter sits in the SMTP delivery path, which changes the engineering priorities: the model is cheap and everything around it is where the work is.
Latency is dominated by feature extraction, not scoring. Scoring a binarized Naive Bayes model is a sparse gather and a sum over roughly 300 non-zero features, which is microseconds. Parsing MIME, normalizing Unicode, resolving the sender ASN, and looking up the recipient’s correspondence history are what fill the budget. The correspondence lookup is the only network hop and it is the reason a cache matters.
Per-message scoring budget, p99 observed:
MIME parse and decode 3.1 ms
normalize + tokenize 1.8 ms
sender ASN + domain age lookup (cached) 0.9 ms
recipient history lookup (Redis) 2.4 ms
feature hashing 0.6 ms
NB score + isotonic transform 0.2 ms
recipient adjustment 0.4 ms
total p99 9.4 ms budget 20 ms
Throughput and footprint:
average inbound 32 msg/s
Monday 09:00 peak 158 msg/s
single 8-core node capacity 410 msg/s
deployed nodes 3 (n+1 redundancy)
model artifact (1.05M cols, float64) 16.8 MB
per-recipient tables (340k mailboxes) 2.1 GB Redis, 45 day TTL
Retraining:
corpus 4.2M messages
featurization (24 workers) 6.2 min
NB fit (single pass, closed form) 71 s
isotonic fit + threshold selection 9 s
full retrain wall clock 8.1 min runs every 6 hours
The retrain cadence is the reason this model is Naive Bayes. Naive Bayes has a closed-form fit: it is a pass of counting, with no iterative optimization and no hyperparameter search once alpha is fixed. That means a full retrain in 8 minutes and, more usefully, incremental updates through partial_fit in seconds, so a campaign that starts at 02:00 can be reflected in the model by 02:20 rather than at tomorrow’s batch. Logistic regression on the same features scores 1.9 points better at the operating point and takes 34 minutes to fit. Against a daily-adapting adversary, 1.9 points of offline recall is not obviously worth a 4x slower adaptation loop, and this tradeoff, not accuracy, is the honest argument for Naive Bayes in 2026.
The feedback loop needs an unbiased ham source. Quarantined mail is never opened, replied to, or foldered, so it never produces a ham label, and every retrain therefore learns from a corpus whose negatives were selected by the previous model. Left alone this drifts in one direction only: features become progressively spammier because the evidence that would contradict them has been filtered out of the training data. The guard is a control sample. For every mailbox, roughly 0.2% of messages that score above the threshold are delivered anyway with a warning banner, and their engagement provides the only unbiased negative labels in the system. It costs a small amount of delivered spam and it is the difference between a filter that converges and one that slowly eats its own tail.
The monitoring signal for silent degradation is the quarantine release rate segmented by sender category, evaluated daily against a 28 day trailing baseline. Global FPR cannot serve this purpose because the threshold is recomputed to hold it constant, so by construction it never moves. Release rate does move, it moves within hours rather than weeks, and segmenting it separates the benign case (a new bulk campaign inflating quarantine volume, so release rate falls) from the dangerous case (a legitimate sender newly landing above the threshold, so release rate in that category spikes). A jump from 0.8% to 2% in the transactional segment is a page, not a dashboard note.
Adaptation speed substitutes for model capacity on adversarial problems, and the exchange rate is favorable more often than people expect. Our logistic regression is 1.9 points better offline and our gradient boosted model 2.6 points better, both measured on a static held-out window. That window cannot measure the thing that matters, which is how fast a model responds to a campaign that did not exist when the test set was cut. Measured on a rolling basis over 90 days of live traffic, the 20 minute incremental update loop recovered more spam than the 2.6 points of static accuracy did, because the modal spam campaign has a lifetime of under 48 hours. Pick your evaluation protocol to match the thing that actually varies.
Naive Bayes spam filtering has an unusually well documented history. Sahami, Dumais, Heckerman and Horvitz published the first careful treatment at AAAI in 1998, and Androutsopoulos et al. followed in 2000 with the cost-sensitive framing that made false positives explicit. Paul Graham's A Plan for Spam (2002) and Better Bayesian Filtering (2003) put it into the hands of everyone running a mail server and introduced several ideas this post uses directly, including token namespacing by message part and retaining punctuation inside tokens. SpamAssassin's Bayes plugin still ships a per-user variant of exactly this model. The modern endpoint is instructive too: Google reported in 2019 that moving Gmail's filtering to TensorFlow-based models caught an additional 100 million spam messages a day on top of an already strong system, at a claimed 99.9% accuracy with a 0.05% false positive rate, which is a useful reality check on the numbers in this post and a reminder that the remaining few points of recall are where the genuinely hard, well-funded part of the problem lives.
Alternative Approaches
| Approach | Recall @ FPR 1e-4 | Fit time (4.2M msgs) | Incremental update | Interpretability | Best fit |
|---|---|---|---|---|---|
| Keyword blocklist | not tunable, 0.41% FPR | none | manual | Total | Never on its own; useful as a pre-filter for known-bad strings |
| Binarized multinomial NB | 94.1% | 71 s | seconds, partial_fit |
High: per-token log-odds | The default: fastest adaptation, explainable, cheap to serve |
| Complement NB | 93.4% | 78 s | seconds | High | Skewed or unbalanced corpora; no advantage at a 47% base rate |
| Logistic regression (SGD, hashed) | 96.0% | 34 min | minutes, warm start | High: signed coefficients | When the corpus is stable enough that a daily retrain is fast enough |
| Linear SVM (hinge, hashed) | 96.3% | 41 min | poor, needs full refit | Medium | Static benchmarks; the refit cost hurts on a moving target |
| LightGBM on hashed features | 96.7% | 2.4 h | none, full refit | Medium: SHAP over features | When header and reputation features dominate and text matters less |
| Fine-tuned DistilBERT | 97.9% | 14 h, 4x A100 | none | Low | Phishing specifically, where semantics beat tokens, as a second-stage model |
For this problem I would ship the binarized Naive Bayes model as the first-stage filter, and the reason is not accuracy, because it is last but one on that column. It is the combination of a 71 second closed-form fit, a partial_fit path that lets a 02:00 campaign be learned by 02:20, a 0.2 millisecond scoring cost that fits inside an SMTP path, and per-token log-odds that populate the quarantine release page without a separate explainability system. On an adversarial problem where the modal campaign lives 48 hours, those properties are worth more than the 2.6 points LightGBM wins by on a static test set.
I would switch under two conditions, and in both cases by adding a stage rather than replacing this one. If phishing becomes the dominant threat rather than bulk commercial spam, the problem changes character: a well-crafted spear-phishing message contains no spammy tokens at all and is identified by semantics and context, which is where a fine-tuned transformer genuinely earns its 14 hour training cost. Run it as a second stage on the 3% of traffic the Naive Bayes model scores in an uncertain band, which keeps the average cost near zero. And if the sender reputation and header features grow to dominate the token features, which happens as authentication standards get better adopted, the feature set stops being a bag of words and starts being structured tabular data, at which point gradient boosting is the natural model and Naive Bayes’s independence assumption stops being a reasonable approximation.
Key Takeaways
- The false positive budget is the specification. “Classify spam” is underspecified and invites optimizing accuracy, which is meaningless at a 47% base rate. Block as much spam as possible subject to a hard FPR ceiling, and set that ceiling from support economics.
- Tune at the operating point.
alphamoved recall at FPR 1e-4 by 7.8 points and accuracy by less than 0.4 points. Any hyperparameter search scored on accuracy or full ROC-AUC will find nothing on this problem. - Binarize the token counts. Presence, not frequency. Worth 9.2 points here, the largest single win, because word repetition is the most extreme violation of the conditional independence assumption.
- Full ROC-AUC hides everything that matters. A 0.0073 improvement in ROC-AUC corresponded to 22.3 points of recall at the deployed threshold. Use partial AUC over the FPR region you operate in.
- Naive Bayes ranks well and calibrates terribly. Correlated features are double-counted, so
predict_probasaturates at 1.0. Threshold on a quantile of the ham score distribution and calibrate isotonically for stability, not for accuracy. - Do not balance the classes. The 47% prior is real information and Naive Bayes uses it correctly. Cost asymmetry belongs in the threshold, not in the training distribution.
- Header and reputation features cover the tokenizer’s blind spot. Image-only spam has almost no tokens. SPF, DKIM, DMARC, sender ASN, and prior correspondence keep working when the text disappears, and are more expensive for an adversary to change.
- Adaptation speed is a first-class model property. A 71 second closed-form fit and a seconds-long
partial_fitbeat 2.6 points of static accuracy when the modal spam campaign lives under 48 hours. - The feedback loop needs an unbiased negative source. Quarantined mail never generates ham labels, so every retrain narrows toward the previous model’s beliefs. A small always-delivered control sample is the cheapest fix.
The counter-intuitive lesson is that the best-known weakness of Naive Bayes turns out not to matter here, while a weakness nobody talks about does. Everyone learns that the conditional independence assumption is violated by natural language, and the reasonable conclusion is that Naive Bayes must therefore be a poor text classifier. It is a poor probability estimator, which is a different claim: the dependence inflates the magnitude of the log-odds without much disturbing their ordering, and a ranking plus a threshold is all a spam filter needs. The weakness that does cost real recall is the smoothing parameter, which barely appears in textbook treatments because it is invisible at any sane threshold and decisive at 1e-4. Once the operating point moves into the tail, the model’s behaviour on tokens seen three times becomes more important than its behaviour on tokens seen three million times.
Frequently Asked Questions
Q: Why not just use logistic regression, which is strictly better calibrated and scored 1.9 points higher?
A: On a static test set it is the better model, and if the corpus were stationary I would ship it. The 34 minute fit against Naive Bayes’s 71 seconds is what decides it: with a modal spam campaign lifetime under 48 hours, the incremental partial_fit path that reflects a new campaign within 20 minutes recovered more spam over 90 days of live traffic than the 1.9 offline points did. If your spam distribution is stable, for example on an internal corporate mail system with no public-facing addresses, reverse this decision.
Q: Why not fine-tune a transformer, given it reached 97.9%?
A: Cost and latency for the first stage, and it is genuinely the right answer for the second. A 20 millisecond p99 budget inside the SMTP path does not accommodate a transformer forward pass, and 14 hours on four A100s per retrain is incompatible with adapting daily. The sensible architecture uses Naive Bayes to route the roughly 3% of traffic in an uncertain score band to a transformer second stage, which concentrates the expensive model where it changes decisions and keeps average cost near zero. That is also where semantics beat tokens, since spear-phishing contains no spammy words at all.
Q: Why report recall at a fixed FPR instead of F1, which is the standard imbalanced-classification metric?
A: F1 is the harmonic mean of precision and recall, which prices one false positive as equal to one false negative. Here a false positive is a lost invoice and a false negative is one extra message in an inbox, a cost ratio closer to 10,000 to 1. Optimizing F1 on this data selects a threshold with a false positive rate around 0.9%, ninety times over budget, while reporting a healthy 0.97. The constraint is not a weighting to be traded off, it is a ceiling, so the metric has to hold it fixed and measure what is achievable underneath.
Q: Is binarized multinomial Naive Bayes not just Bernoulli Naive Bayes?
A: They are close and the difference matters at this threshold. Bernoulli Naive Bayes explicitly models the absence of every vocabulary term, adding a log(1 - P(f | class)) penalty for each of the roughly 1.05 million features a message does not contain. With a vocabulary that size and messages averaging 300 distinct features, those absence terms dominate the score and make it mostly a function of message length. Binarized multinomial scores only the features present, with each counted once. Measured here: Bernoulli reaches 88.7% recall at the budget, binarized multinomial 94.1%, and the gap is almost entirely the length sensitivity.
Q: How do you keep the filter from learning its own output?
A: Deliberately delivered control samples. Quarantined messages generate no engagement and therefore no ham labels, so a retrain’s negatives are always drawn from what the previous model let through, and features drift monotonically spammier across generations. Delivering roughly 0.2% of above-threshold messages anyway, with a warning banner, produces the only unbiased negatives in the system. The cost is a small amount of delivered spam; the benefit is that the model converges instead of narrowing.
Q: What breaks first in production?
A: A large legitimate sender changing sending infrastructure. Every reputation feature (sender_asn, domain_age_days, spf_result, prior_inbound_from_domain) resets at once, and that sender’s transactional mail starts scoring like first-contact bulk mail from an unknown network. The global FPR does not move, because the threshold is recomputed to hold it. What moves is the release rate inside that sender’s category, within hours. Monitoring release rate by sender category rather than global FPR is what turns this from a support ticket next week into a page tonight.
Interview Questions
Q: Your spam corpus is 47% positive and your model reports 96% accuracy. Your manager is satisfied. Convince them they should not be.
Expected depth: Establish the majority-class floor of 53% first, so 96% is measured against the right baseline. Then make the cost asymmetry explicit and argue that the deployable metric is recall at a fixed false positive rate, showing that a 96% accurate model can sit at 71.8% recall once the FPR ceiling is enforced. Strong answers note that precision becomes pinned near 100% by the constraint and therefore cannot discriminate between models, and that full ROC-AUC is dominated by operating points nobody would deploy, so partial AUC over the low-FPR region is the right aggregate.
Q: Naive Bayes assumes conditional independence, which is obviously false for natural language. Why does it work for spam filtering anyway, and where does the violation actually cost you?
Expected depth: Separate ranking quality from probability calibration. The dependence between co-occurring tokens inflates the magnitude of summed log-likelihood ratios without greatly disturbing their ordering, and a filter needs a ranking plus a threshold, so the classifier survives what the density estimator does not. Cite the overconfidence result (Zadrozny and Elkan, 2001) and the saturation of predict_proba at 1.0. For where it costs: word repetition inside a document is the most extreme violation, which is what binarization patches, and correlated feature groups like wire/transfer still get double-counted. Top answers mention that isotonic calibration fixes the probabilities without changing any ranking, hence without changing recall at any FPR.
Q: Walk me through how you would split this dataset, and name two things that leak if you get it wrong.
Expected depth: Time-ordered split with an embargo, plus near-duplicate grouping so a campaign cannot straddle the boundary. The two leaks: campaign duplication, where a 40,000 message template appears on both sides and the model is credited for memorization worth about 11 points of apparent recall; and adversary-temporal leakage, where training on future messages lets the model see campaigns that had not launched. A third, and the strongest thing to raise unprompted, is verdict-header leakage from X-Spam-* headers written by the incumbent filter, which are present offline and absent at SMTP time.
Q: You need to pick the Laplace smoothing parameter. How, and why does it matter more here than on a typical text classification task?
Expected depth: Select it by recall at the deployed FPR, not by accuracy or AUC, and be able to say why: at 1e-4 the threshold sits in the extreme tail of the ham score distribution, where individual messages are decided by a few rare tokens. Explain the two failure modes concretely. Too little smoothing leaves a token seen three times in spam and never in ham with an unbounded log-likelihood ratio that single-handedly blocks a legitimate message. Too much flattens the rare discriminative tokens that carry most of the signal on short messages. The measured shape (roughly 8 points of recall spread, under half a point of accuracy spread) is the punchline.
Q: Spammers adapt within days. How does that change your model choice, your evaluation protocol, and your training data pipeline?
Expected depth: All three should move. Model choice: weight adaptation speed alongside static accuracy, which is what makes a closed-form counting model with a partial_fit path competitive against a strictly more accurate boosted or transformer model. Evaluation: a single static held-out window cannot measure response time to novel campaigns, so evaluate on a rolling forward basis and report recall as a function of campaign age. Data pipeline: recognize the feedback loop, where quarantined mail yields no ham labels and each generation trains on the previous model’s beliefs, and propose the always-delivered control sample as the unbiased negative source. Mentioning tokenizer-level evasion (homoglyphs, zero-width characters, image-only bodies) and the corresponding countermeasures rounds out a complete answer.