TExcelTAD
Home › ML Projects: 15 End-to-End Builds › Project 5: Email Spam Detection

Project 5: Email Spam Detection

A company of 400 people runs its own mail gateway, and the IT team wants a spam filter in front of the inboxes. The request comes with one hard rule from the staff: a real email in the spam folder is much worse than a spam email in the inbox. A missed invoice or a lost job offer costs more than deleting an advert. This intermediate project builds that filter end to end: a labelled corpus, baselines, a threshold chosen for a strict precision target, a test month used once, then the part most tutorials skip: the spammers notice the filter and start writing fr33 and c.l.i.c.k, and the filter has to be fixed without breaking it. It ends with a FastAPI endpoint.

The techniques are taught elsewhere and only used here: multinomial naive Bayes (its toy spam example has eight messages), TF-IDF, linear text classifiers (which classify support tickets by macro-F1 with no costs attached), precision-recall curves and choosing a threshold. What is new is the asymmetric operating point, months as splits, and an adversary that changes the input after launch.

Goal and success criteria

Fixed before any model is trained:

Criterion Target Measured on
precision of the spam folder at least 0.99 (at most 1 real email per 100 flagged) month 5, 1,000 emails, used once
spam recall at that threshold at least 0.75 same
newsletters the user signed up for almost never flagged (report the count) same, the newsletter slice
after spammers adapt precision still at least 0.99, recall at least 0.75 month 7, disguised spam, used once
service rejects empty input with 422, returns folder, score, threshold, version the API test in Step 4

Accuracy is not on the list: with 35 % spam, a filter that flags nothing is 65 % accurate and a filter that flags everything with a word like "free" is useless. The threshold is a product decision, written down as "precision 0.99", and the model is judged by the recall it can deliver at that precision.

The data

Real email is personal data, so the lesson generates it. make_emails builds each email from one to three sentences, drawn from five pools: work, chat, notice (password expiry, shipping, sign-in alerts), promo and scam. Ham mixes the first four, so about a third of the real emails are newsletters with offers and prize draws the user asked for. Spam is mostly scam sentences, but some of it is built only from promo, work or chat sentences: a "harmless-looking" spam with nothing to catch (a scam opener like "are you free for a quick call" is exactly that). The generator records each email's kind so the error analysis can slice by it; a real project would have to label such slices.

The timeline is that of a real launch:

Split Emails Labels Role
months 1 to 3 3,000 the users' "report spam" button, 3 % wrong training
month 4 1,000 checked by two reviewers validation: model and threshold
month 5 1,000 checked test, once
month 6 1,000 checked, after launch; spammers disguise 60 % of their tell-tale words validation for the fix
month 7 1,000 checked; disguised as month 6 test of the fix, once

Splitting by month rather than at random matters for spam: campaigns send thousands of near-identical messages within days, and a random split puts copies of the same campaign on both sides (split strategies). Public corpora for a real version: the SMS Spam Collection on UCI (CC BY 4.0) and the Enron-Spam corpus (Metsis, Androutsopoulos and Paliouras, 2006, built from the public Enron mails; it states no open licence, so treat it as research data). Corporate mail needs a legal basis, data minimisation and a retention limit before anyone reads it to label it (privacy and consent). All scores below are about this generator, not about real mail.

emailraw text normalisefr33, f.r.e.e -> free featuresword 1-2 grams modelscore 0-1 threshold tP 0.99 on val spam folder inbox score at or above tbelow t

Step 1: explore, and two baselines

Look at the splits and a few emails, then score two baselines on month 4: a keyword rule (what an administrator writes on day one) and naive Bayes on word counts. Each model is summarised by its PR-AUC and by the number that matters here, the best recall among thresholds whose validation precision is at least 0.99.

python · try it yourself
import re
import numpy as np

SLOTS = {"name": "anna ben chloe david emma", "day": "monday tuesday wednesday thursday friday",
         "doc": "report slides budget contract draft", "prize": "iphone voucher holiday laptop",
         "bad": "secure-login.example claim-now.example pay-fee.example", "good": "intranet.example portal.example shop.example"}
POOLS = {  # sentence pools, separated by "|"; {slot} is filled at random
    "work": "can we move the {doc} review to {day}|the {doc} is attached, please check it|reminder: team meeting on {day}"
            "|the invoice was paid on {day}, thanks|please send the {doc} before {day}",
    "chat": "lunch on {day}?|are you free for a quick call|{name} says hi|thanks for your help {name}",
    "notice": "your password expires on {day}, change it at {good}|your order has shipped, track it at {good}"
              "|new sign-in to your account, if this was you no action is needed",
    "promo": "members offer: 20% off this week|free shipping on all orders|win a {prize} in our prize draw"
             "|limited offer, ends {day}|click here to see the deals",
    "scam": "you won a free {prize}, click here to claim now|urgent: verify your password at {bad}|get a loan today, "
            "no credit check|your parcel is on hold, pay the fee at {bad}|cheap pills, order now"
            "|invoice overdue, pay now at {bad}|claim your cash prize at {bad}"}
MIX = {0: (["work", "chat", "notice", "promo"], [0.4, 0.25, 0.15, 0.2]),   # ham, with newsletters the user wants
       1: (["scam", "promo", "work", "chat"], [0.6, 0.25, 0.1, 0.05])}     # spam, some of it harmless-looking
words = lambda ps: set(re.findall(r"[a-z]+", re.sub(r"\{\w+\}", "", " ".join(POOLS[p] for p in ps))))
DISGUISED = words(["scam"]) - words(["work", "chat", "notice"])          # words only scams use

def disguise(w, rng):                                                      # fr33, f.r.e.e or f*ree
    k = rng.integers(3)
    return w.translate(str.maketrans("eioa", "310@")) if k == 0 else ".".join(w) if k == 1 else w[0] + "*" + w[1:]

def make_emails(rng, n, obf=0.0, label_noise=0.0):
    """n emails, 35 % spam: texts, labels, and each email's kind (for error analysis)."""
    y = (rng.random(n) < 0.35).astype(int)
    texts, kinds = [], []
    for lab in y:
        used = [str(rng.choice(MIX[lab][0], p=MIX[lab][1])) for _ in range(rng.integers(1, 4))]
        text = ". ".join(str(rng.choice(POOLS[p].split("|"))) for p in used)
        text = re.sub(r"\{(\w+)\}", lambda m: str(rng.choice(SLOTS[m.group(1)].split())), text)
        if lab and obf:
            text = " ".join(disguise(w, rng) if re.sub(r"[^a-z]", "", w) in DISGUISED and rng.random() < obf else w
                            for w in text.split())
        texts.append(text)
        kinds.append(("scam" if "scam" in used else "harmless-looking") if lab else ("newsletter" if "promo" in used else "normal"))
    return texts, np.where(rng.random(n) < label_noise, 1 - y, y), np.array(kinds)

def months(seed=5):
    rng = np.random.default_rng(seed)
    return {"train": make_emails(rng, 3000, label_noise=0.03), "val": make_emails(rng, 1000), "test": make_emails(rng, 1000),
            "month6": make_emails(rng, 1000, obf=0.6), "month7": make_emails(rng, 1000, obf=0.6)}

from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.metrics import precision_score, recall_score, average_precision_score, precision_recall_curve

def recall_at_precision(y, p, target=0.99):
    P, R, T = precision_recall_curve(y, p)
    ok = np.where(P[:-1] >= target)[0]
    return R[ok].max() if len(ok) else 0.0

data = months()
for name, (X, y, kind) in data.items():
    print(f"{name:7s} {len(y)} emails, spam share {y.mean():.3f}")
X_tr, y_tr, _ = data["train"]
X_va, y_va, k_va = data["val"]
for i in range(4):
    print(f"  [{'spam' if y_tr[i] else 'ham '}] {X_tr[i]}")
print("validation kinds:", {k: int((k_va == k).sum()) for k in ["normal", "newsletter", "scam", "harmless-looking"]})

RULE = {"free", "win", "won", "prize", "claim", "click", "offer", "loan"}
rule = np.array([int(bool(RULE & set(re.findall(r"[a-z]+", t)))) for t in X_va])
print(f"keyword rule: precision {precision_score(y_va, rule):.3f}, recall {recall_score(y_va, rule):.3f}")
for name, model in [("naive Bayes, counts", make_pipeline(CountVectorizer(), MultinomialNB())),
                    ("logistic, tf-idf 1-2 grams", make_pipeline(TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True),
                                                                 LogisticRegression(C=10, max_iter=2000)))]:
    p = model.fit(X_tr, y_tr).predict_proba(X_va)[:, 1]
    print(f"{name:27s} PR-AUC {average_precision_score(y_va, p):.3f}, "
          f"recall at precision >= 0.99: {recall_at_precision(y_va, p):.3f}")
train   3000 emails, spam share 0.362
val     1000 emails, spam share 0.352
test    1000 emails, spam share 0.352
month6  1000 emails, spam share 0.351
month7  1000 emails, spam share 0.333
  [ham ] win a laptop in our prize draw
  [ham ] free shipping on all orders. please send the budget before friday
  [ham ] please send the report before tuesday. the slides is attached, please check it
  [spam] free shipping on all orders. you won a free iphone, click here to claim now
validation kinds: {'normal': 421, 'newsletter': 227, 'scam': 285, 'harmless-looking': 67}
keyword rule: precision 0.490, recall 0.795
naive Bayes, counts         PR-AUC 0.958, recall at precision >= 0.99: 0.812
logistic, tf-idf 1-2 grams  PR-AUC 0.953, recall at precision >= 0.99: 0.781

The months have similar spam shares (0.33 to 0.36), so the splits are comparable. The keyword rule catches 0.795 of the spam but half of what it flags is real mail (precision 0.490): the newsletters use the same words. Both learned models rank well (PR-AUC about 0.95), and at precision 0.99 they keep about 0.8 of the spam. Note the ceiling: 67 of the 352 validation spams are harmless-looking, 19 %, and no text model can find those without other signals.

Step 2: choose the operating point on validation, test once

The strict precision target means the threshold is chosen, not left at 0.5. The lab shows why with two score distributions (35 % positives, separation 3): at the default threshold 1.5 precision is 0.868 and recall 0.937; move the threshold to 3 and precision rises to 0.994 while recall falls to 0.494. Every point of the curve is a different product.

05005scorecountScores by true classpositive →← negativenegativepositivepredicted +predicted −actual posactual neg328TP22FN50FP600TNprecision 0.868 recall 0.937 F1 0.9010.00.51.00.00.51.0false positive rateTPRROC curveAUC 0.985- - chance0.00.51.00.00.51.0recallprecisionPrecision-recallAP 0.974- - chance

Now the real models. Five candidates are fitted on months 1 to 3; for each, operating_point finds the threshold with the highest validation recall among those with validation precision at least 0.99. The winner and its threshold are frozen, and month 5 is scored once.

python · try it yourself
import re
import numpy as np

SLOTS = {"name": "anna ben chloe david emma", "day": "monday tuesday wednesday thursday friday",
         "doc": "report slides budget contract draft", "prize": "iphone voucher holiday laptop",
         "bad": "secure-login.example claim-now.example pay-fee.example", "good": "intranet.example portal.example shop.example"}
POOLS = {  # sentence pools, separated by "|"; {slot} is filled at random
    "work": "can we move the {doc} review to {day}|the {doc} is attached, please check it|reminder: team meeting on {day}"
            "|the invoice was paid on {day}, thanks|please send the {doc} before {day}",
    "chat": "lunch on {day}?|are you free for a quick call|{name} says hi|thanks for your help {name}",
    "notice": "your password expires on {day}, change it at {good}|your order has shipped, track it at {good}"
              "|new sign-in to your account, if this was you no action is needed",
    "promo": "members offer: 20% off this week|free shipping on all orders|win a {prize} in our prize draw"
             "|limited offer, ends {day}|click here to see the deals",
    "scam": "you won a free {prize}, click here to claim now|urgent: verify your password at {bad}|get a loan today, "
            "no credit check|your parcel is on hold, pay the fee at {bad}|cheap pills, order now"
            "|invoice overdue, pay now at {bad}|claim your cash prize at {bad}"}
MIX = {0: (["work", "chat", "notice", "promo"], [0.4, 0.25, 0.15, 0.2]),   # ham, with newsletters the user wants
       1: (["scam", "promo", "work", "chat"], [0.6, 0.25, 0.1, 0.05])}     # spam, some of it harmless-looking
words = lambda ps: set(re.findall(r"[a-z]+", re.sub(r"\{\w+\}", "", " ".join(POOLS[p] for p in ps))))
DISGUISED = words(["scam"]) - words(["work", "chat", "notice"])          # words only scams use

def disguise(w, rng):                                                      # fr33, f.r.e.e or f*ree
    k = rng.integers(3)
    return w.translate(str.maketrans("eioa", "310@")) if k == 0 else ".".join(w) if k == 1 else w[0] + "*" + w[1:]

def make_emails(rng, n, obf=0.0, label_noise=0.0):
    """n emails, 35 % spam: texts, labels, and each email's kind (for error analysis)."""
    y = (rng.random(n) < 0.35).astype(int)
    texts, kinds = [], []
    for lab in y:
        used = [str(rng.choice(MIX[lab][0], p=MIX[lab][1])) for _ in range(rng.integers(1, 4))]
        text = ". ".join(str(rng.choice(POOLS[p].split("|"))) for p in used)
        text = re.sub(r"\{(\w+)\}", lambda m: str(rng.choice(SLOTS[m.group(1)].split())), text)
        if lab and obf:
            text = " ".join(disguise(w, rng) if re.sub(r"[^a-z]", "", w) in DISGUISED and rng.random() < obf else w
                            for w in text.split())
        texts.append(text)
        kinds.append(("scam" if "scam" in used else "harmless-looking") if lab else ("newsletter" if "promo" in used else "normal"))
    return texts, np.where(rng.random(n) < label_noise, 1 - y, y), np.array(kinds)

def months(seed=5):
    rng = np.random.default_rng(seed)
    return {"train": make_emails(rng, 3000, label_noise=0.03), "val": make_emails(rng, 1000), "test": make_emails(rng, 1000),
            "month6": make_emails(rng, 1000, obf=0.6), "month7": make_emails(rng, 1000, obf=0.6)}

from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.metrics import precision_recall_curve, confusion_matrix

def operating_point(y, p, target=0.99):
    """The lowest threshold whose precision is >= target (highest recall among those)."""
    P, R, T = precision_recall_curve(y, p)
    ok = np.where(P[:-1] >= target)[0]
    i = ok[np.argmax(R[ok])]
    return T[i], P[i], R[i]

data = months()
X_tr, y_tr, _ = data["train"]
X_va, y_va, _ = data["val"]
X_te, y_te, k_te = data["test"]
candidates = {f"NB alpha={a}": make_pipeline(CountVectorizer(ngram_range=(1, 2)), MultinomialNB(alpha=a)) for a in [0.1, 1.0]}
candidates.update({f"LR C={C}": make_pipeline(TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True),
                                              LogisticRegression(C=C, max_iter=2000)) for C in [1, 10, 100]})
best = None
for name, model in candidates.items():
    p = model.fit(X_tr, y_tr).predict_proba(X_va)[:, 1]
    thr, prec, rec = operating_point(y_va, p)
    print(f"{name:12s} validation: threshold {thr:.3f}, precision {prec:.3f}, recall {rec:.3f}")
    if best is None or rec > best[0]:
        best = (rec, name, model, thr)
rec, name, model, thr = best
p = model.predict_proba(X_te)[:, 1]
flag = (p >= thr).astype(int)
tn, fp, fn, tp = confusion_matrix(y_te, flag).ravel()
print(f"chosen: {name}, threshold {thr:.3f}")
print(f"TEST (month 5, used once): precision {tp / (tp + fp):.3f}, recall {tp / (tp + fn):.3f}, "
      f"ham in the spam folder {fp} of {tn + fp}, spam in the inbox {fn} of {fn + tp}")
for k in ["scam", "harmless-looking"]:
    m = (k_te == k) & (y_te == 1)
    print(f"  recall on {k} spam: {flag[m].mean():.3f} ({m.sum()} emails)")
m = (k_te == "newsletter") & (y_te == 0)
print(f"  newsletters flagged: {flag[m].sum()} of {m.sum()}")
NB alpha=0.1 validation: threshold 0.996, precision 0.993, recall 0.810
NB alpha=1.0 validation: threshold 0.997, precision 0.993, recall 0.810
LR C=1       validation: threshold 0.518, precision 0.996, recall 0.807
LR C=10      validation: threshold 0.663, precision 0.993, recall 0.781
LR C=100     validation: threshold 0.941, precision 0.992, recall 0.665
chosen: NB alpha=0.1, threshold 0.996
TEST (month 5, used once): precision 0.996, recall 0.781, ham in the spam folder 1 of 648, spam in the inbox 77 of 352
  recall on scam spam: 1.000 (274 emails)
  recall on harmless-looking spam: 0.013 (78 emails)
  newsletters flagged: 1 of 220

Naive Bayes with alpha=0.1 wins on validation (recall 0.810; logistic regression with C=1 is a close 0.807, so either would be a fair choice). On the untouched month 5 it puts 1 of 648 real emails in the spam folder (precision 0.996) and catches 0.781 of the spam: both criteria met. The slices explain the recall: every scam email is caught (1.000), the 78 harmless-looking ones almost never (0.013), and only 1 of 220 newsletters is flagged. Two details to note. The naive Bayes threshold is 0.996, not 0.5: its probabilities are extreme because it multiplies many word likelihoods as if they were independent, so read them as a ranking (calibration can fix them if the scores are shown to people). And the precision estimate rests on few errors: 1 false positive in 273 flags. A second false positive would still pass; ten would not, so keep monitoring it after launch.

Step 3: the spammers adapt

A month after launch, the senders whose mail no longer arrives change their text: in month 6, 60 % of the words that only scams use are disguised (fr33, f.r.e.e, f*ree). To a word model v3r1fy is an unknown token, so the email loses its strongest evidence. This is an adversarial form of distribution shift (security of ML systems covers evasion attacks in general). Two fixes are compared: a hand-written normalise step that undoes the three tricks (text normalisation), and character n-grams, which still share pieces such as pi and ll with the clean word. Month 6 (labelled after launch) chooses the variant and its threshold; month 7 tests it once.

python · try it yourself
import re
import numpy as np

SLOTS = {"name": "anna ben chloe david emma", "day": "monday tuesday wednesday thursday friday",
         "doc": "report slides budget contract draft", "prize": "iphone voucher holiday laptop",
         "bad": "secure-login.example claim-now.example pay-fee.example", "good": "intranet.example portal.example shop.example"}
POOLS = {  # sentence pools, separated by "|"; {slot} is filled at random
    "work": "can we move the {doc} review to {day}|the {doc} is attached, please check it|reminder: team meeting on {day}"
            "|the invoice was paid on {day}, thanks|please send the {doc} before {day}",
    "chat": "lunch on {day}?|are you free for a quick call|{name} says hi|thanks for your help {name}",
    "notice": "your password expires on {day}, change it at {good}|your order has shipped, track it at {good}"
              "|new sign-in to your account, if this was you no action is needed",
    "promo": "members offer: 20% off this week|free shipping on all orders|win a {prize} in our prize draw"
             "|limited offer, ends {day}|click here to see the deals",
    "scam": "you won a free {prize}, click here to claim now|urgent: verify your password at {bad}|get a loan today, "
            "no credit check|your parcel is on hold, pay the fee at {bad}|cheap pills, order now"
            "|invoice overdue, pay now at {bad}|claim your cash prize at {bad}"}
MIX = {0: (["work", "chat", "notice", "promo"], [0.4, 0.25, 0.15, 0.2]),   # ham, with newsletters the user wants
       1: (["scam", "promo", "work", "chat"], [0.6, 0.25, 0.1, 0.05])}     # spam, some of it harmless-looking
words = lambda ps: set(re.findall(r"[a-z]+", re.sub(r"\{\w+\}", "", " ".join(POOLS[p] for p in ps))))
DISGUISED = words(["scam"]) - words(["work", "chat", "notice"])          # words only scams use

def disguise(w, rng):                                                      # fr33, f.r.e.e or f*ree
    k = rng.integers(3)
    return w.translate(str.maketrans("eioa", "310@")) if k == 0 else ".".join(w) if k == 1 else w[0] + "*" + w[1:]

def make_emails(rng, n, obf=0.0, label_noise=0.0):
    """n emails, 35 % spam: texts, labels, and each email's kind (for error analysis)."""
    y = (rng.random(n) < 0.35).astype(int)
    texts, kinds = [], []
    for lab in y:
        used = [str(rng.choice(MIX[lab][0], p=MIX[lab][1])) for _ in range(rng.integers(1, 4))]
        text = ". ".join(str(rng.choice(POOLS[p].split("|"))) for p in used)
        text = re.sub(r"\{(\w+)\}", lambda m: str(rng.choice(SLOTS[m.group(1)].split())), text)
        if lab and obf:
            text = " ".join(disguise(w, rng) if re.sub(r"[^a-z]", "", w) in DISGUISED and rng.random() < obf else w
                            for w in text.split())
        texts.append(text)
        kinds.append(("scam" if "scam" in used else "harmless-looking") if lab else ("newsletter" if "promo" in used else "normal"))
    return texts, np.where(rng.random(n) < label_noise, 1 - y, y), np.array(kinds)

def months(seed=5):
    rng = np.random.default_rng(seed)
    return {"train": make_emails(rng, 3000, label_noise=0.03), "val": make_emails(rng, 1000), "test": make_emails(rng, 1000),
            "month6": make_emails(rng, 1000, obf=0.6), "month7": make_emails(rng, 1000, obf=0.6)}

from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline, make_union
from sklearn.metrics import precision_recall_curve

def operating_point(y, p, target=0.99):
    P, R, T = precision_recall_curve(y, p)
    ok = np.where(P[:-1] >= target)[0]
    i = ok[np.argmax(R[ok])]
    return T[i], P[i], R[i]

UNLEET = str.maketrans("310@", "eioa")
def normalise(t):
    t = re.sub(r"\b(?:\w[.*]){2,}\w\b", lambda m: re.sub(r"[.*]", "", m.group()), t.lower())   # f.r.e.e -> free
    t = t.replace("*", "")                                                                   # f*ree -> free
    return re.sub(r"[\w@]+", lambda m: m.group().translate(UNLEET)                           # fr33 -> free
                  if re.search(r"[a-z]", m.group()) and re.search(r"[0-9@]", m.group()) else m.group(), t)

print(normalise("Cl@1m your c.a.s.h p*rize, 20% off"))
data = months()
(X_tr, y_tr, _), (X_va, y_va, _) = data["train"], data["val"]
(X_m6, y_m6, _), (X_m7, y_m7, k_m7) = data["month6"], data["month7"]
print("month 6 spam:", [t for t, l in zip(X_m6, y_m6) if l][1])

launched = make_pipeline(CountVectorizer(ngram_range=(1, 2)), MultinomialNB(alpha=0.1)).fit(X_tr, y_tr)
thr0 = operating_point(y_va, launched.predict_proba(X_va)[:, 1])[0]
p6 = launched.predict_proba(X_m6)[:, 1]
print(f"launched model on month 6 at its threshold: recall {(p6[y_m6 == 1] >= thr0).mean():.3f}, "
      f"ham flagged {(p6[y_m6 == 0] >= thr0).sum()}")

tfidf = lambda **kw: TfidfVectorizer(sublinear_tf=True, **kw)
variants = {
    "words (launched)": make_pipeline(CountVectorizer(ngram_range=(1, 2)), MultinomialNB(alpha=0.1)),
    "normalise + words": make_pipeline(CountVectorizer(preprocessor=normalise, ngram_range=(1, 2)), MultinomialNB(alpha=0.1)),
    "char 2-5 grams": make_pipeline(tfidf(analyzer="char_wb", ngram_range=(2, 5)), LogisticRegression(C=10, max_iter=2000)),
    "normalise + words + chars": make_pipeline(make_union(tfidf(preprocessor=normalise, ngram_range=(1, 2)),
                                               tfidf(preprocessor=normalise, analyzer="char_wb", ngram_range=(2, 5))),
                                               LogisticRegression(C=10, max_iter=2000)),
}
best = None
for name, model in variants.items():
    model.fit(X_tr, y_tr)
    _, _, r_va = operating_point(y_va, model.predict_proba(X_va)[:, 1])
    thr, prec, rec = operating_point(y_m6, model.predict_proba(X_m6)[:, 1])
    print(f"{name:26s} recall at precision >= 0.99: month 4 {r_va:.3f}, month 6 {rec:.3f}")
    if best is None or rec > best[0]:
        best = (rec, name, model, thr)
rec, name, model, thr = best
flag = model.predict_proba(X_m7)[:, 1] >= thr
tp, fp = (flag & (y_m7 == 1)).sum(), (flag & (y_m7 == 0)).sum()
print(f"chosen on month 6: {name}; TEST month 7: precision {tp / (tp + fp):.3f}, recall {tp / (y_m7 == 1).sum():.3f}")
for k in ["scam", "harmless-looking"]:
    m = (k_m7 == k) & (y_m7 == 1)
    print(f"  month 7 recall on {k} spam: {flag[m].mean():.3f} ({m.sum()} emails)")
missed = [t for t, f, l, k in zip(X_m7, flag, y_m7, k_m7) if l and not f and k == "scam"]
print("  missed scam emails:", len(missed), missed[:2])
claim your cash prize, 20% off
month 6 spam: cheap pills, order n*ow. thanks for your help ben
launched model on month 6 at its threshold: recall 0.647, ham flagged 1
words (launched)           recall at precision >= 0.99: month 4 0.810, month 6 0.664
normalise + words          recall at precision >= 0.99: month 4 0.810, month 6 0.752
char 2-5 grams             recall at precision >= 0.99: month 4 0.812, month 6 0.732
normalise + words + chars  recall at precision >= 0.99: month 4 0.778, month 6 0.741
chosen on month 6: normalise + words; TEST month 7: precision 1.000, recall 0.793
  month 7 recall on scam spam: 0.992 (263 emails)
  month 7 recall on harmless-looking spam: 0.043 (70 emails)
  missed scam emails: 2 ['free shipping on all orders. can we move the budget review to tuesday. c*heap p*ills, order n.o.w', 'can we move the draft review to tuesday. cheap p1lls, order now']

At its frozen threshold the launched model's recall falls from 0.781 to 0.647 on month 6, with precision intact: disguises make spam look less spammy, they do not make ham look like spam. Normalisation recovers most of it (0.752 on month 6) without losing anything on clean month 4; character n-grams alone recover less (0.732), and the union of both is not better than normalisation alone here (0.741). On month 7 the chosen pipeline keeps precision at 1.000 with recall 0.793, both targets met again. The error analysis shows what is left: 0.992 of scam spam is caught, and the misses are 2 scams buried under a work sentence plus the 70 harmless-looking spams (recall 0.043), which need signals outside the text.

Two honest caveats. The normaliser was written after seeing the attack, so it only undoes the tricks we know; character n-grams are the more general defence when the next trick is new, and a production filter would keep both and retrain on recent labelled months (retraining). And month 6 was used to choose, so its numbers are optimistic; month 7 is the honest one.

Step 4: the service

The mail gateway calls an HTTP endpoint for each incoming email. The service loads the pipeline and the frozen threshold at start-up (here it rebuilds them from the same seed, a shortcut for a self-contained example; a real service loads the saved artefact, as in saving models), validates the request with Pydantic, and returns the folder, the score, the threshold and the model version, so every decision can be traced later. It runs in the browser through httpx.ASGITransport, as in the FastAPI lesson.

python · try it yourself
import re
import numpy as np

SLOTS = {"name": "anna ben chloe david emma", "day": "monday tuesday wednesday thursday friday",
         "doc": "report slides budget contract draft", "prize": "iphone voucher holiday laptop",
         "bad": "secure-login.example claim-now.example pay-fee.example", "good": "intranet.example portal.example shop.example"}
POOLS = {  # sentence pools, separated by "|"; {slot} is filled at random
    "work": "can we move the {doc} review to {day}|the {doc} is attached, please check it|reminder: team meeting on {day}"
            "|the invoice was paid on {day}, thanks|please send the {doc} before {day}",
    "chat": "lunch on {day}?|are you free for a quick call|{name} says hi|thanks for your help {name}",
    "notice": "your password expires on {day}, change it at {good}|your order has shipped, track it at {good}"
              "|new sign-in to your account, if this was you no action is needed",
    "promo": "members offer: 20% off this week|free shipping on all orders|win a {prize} in our prize draw"
             "|limited offer, ends {day}|click here to see the deals",
    "scam": "you won a free {prize}, click here to claim now|urgent: verify your password at {bad}|get a loan today, "
            "no credit check|your parcel is on hold, pay the fee at {bad}|cheap pills, order now"
            "|invoice overdue, pay now at {bad}|claim your cash prize at {bad}"}
MIX = {0: (["work", "chat", "notice", "promo"], [0.4, 0.25, 0.15, 0.2]),   # ham, with newsletters the user wants
       1: (["scam", "promo", "work", "chat"], [0.6, 0.25, 0.1, 0.05])}     # spam, some of it harmless-looking
words = lambda ps: set(re.findall(r"[a-z]+", re.sub(r"\{\w+\}", "", " ".join(POOLS[p] for p in ps))))
DISGUISED = words(["scam"]) - words(["work", "chat", "notice"])          # words only scams use

def disguise(w, rng):                                                      # fr33, f.r.e.e or f*ree
    k = rng.integers(3)
    return w.translate(str.maketrans("eioa", "310@")) if k == 0 else ".".join(w) if k == 1 else w[0] + "*" + w[1:]

def make_emails(rng, n, obf=0.0, label_noise=0.0):
    """n emails, 35 % spam: texts, labels, and each email's kind (for error analysis)."""
    y = (rng.random(n) < 0.35).astype(int)
    texts, kinds = [], []
    for lab in y:
        used = [str(rng.choice(MIX[lab][0], p=MIX[lab][1])) for _ in range(rng.integers(1, 4))]
        text = ". ".join(str(rng.choice(POOLS[p].split("|"))) for p in used)
        text = re.sub(r"\{(\w+)\}", lambda m: str(rng.choice(SLOTS[m.group(1)].split())), text)
        if lab and obf:
            text = " ".join(disguise(w, rng) if re.sub(r"[^a-z]", "", w) in DISGUISED and rng.random() < obf else w
                            for w in text.split())
        texts.append(text)
        kinds.append(("scam" if "scam" in used else "harmless-looking") if lab else ("newsletter" if "promo" in used else "normal"))
    return texts, np.where(rng.random(n) < label_noise, 1 - y, y), np.array(kinds)

def months(seed=5):
    rng = np.random.default_rng(seed)
    return {"train": make_emails(rng, 3000, label_noise=0.03), "val": make_emails(rng, 1000), "test": make_emails(rng, 1000),
            "month6": make_emails(rng, 1000, obf=0.6), "month7": make_emails(rng, 1000, obf=0.6)}

import asyncio, httpx
from fastapi import FastAPI
from pydantic import BaseModel, Field
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
from sklearn.metrics import precision_recall_curve

UNLEET = str.maketrans("310@", "eioa")
def normalise(t):
    t = re.sub(r"\b(?:\w[.*]){2,}\w\b", lambda m: re.sub(r"[.*]", "", m.group()), t.lower())
    t = t.replace("*", "")
    return re.sub(r"[\w@]+", lambda m: m.group().translate(UNLEET)
                  if re.search(r"[a-z]", m.group()) and re.search(r"[0-9@]", m.group()) else m.group(), t)

# start-up: in production, load the saved pipeline and its threshold; here we rebuild them (same seed, same result)
data = months()
MODEL = make_pipeline(CountVectorizer(preprocessor=normalise, ngram_range=(1, 2)), MultinomialNB(alpha=0.1))
MODEL.fit(*data["train"][:2])
X6, y6, _ = data["month6"]
P, R, T = precision_recall_curve(y6, MODEL.predict_proba(X6)[:, 1])
ok = np.where(P[:-1] >= 0.99)[0]
THRESHOLD, VERSION = float(T[ok[np.argmax(R[ok])]]), "spam-nb-2"

class Email(BaseModel):
    text: str = Field(min_length=1, max_length=20_000)

class Verdict(BaseModel):
    folder: str
    spam_score: float
    threshold: float
    model_version: str

app = FastAPI(title="spam-filter")

@app.post("/classify", response_model=Verdict)
async def classify(email: Email):
    score = float(MODEL.predict_proba([email.text])[0, 1])
    return Verdict(folder="spam" if score >= THRESHOLD else "inbox", spam_score=round(score, 4),
                   threshold=round(THRESHOLD, 4), model_version=VERSION)

async def main():
    async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
        for text in ["URGENT: v3r1fy your p@ssword at secure-login.example",
                     "members offer: 20% off this week. free shipping on all orders",
                     "can we move the budget review to friday", ""]:
            r = await client.post("/classify", json={"text": text})
            body = r.json()
            print(r.status_code, body if r.status_code == 200 else body["detail"][0]["msg"], "<-", repr(text[:40]))

asyncio.run(main())
200 {'folder': 'spam', 'spam_score': 1.0, 'threshold': 0.99, 'model_version': 'spam-nb-2'} <- 'URGENT: v3r1fy your p@ssword at secure-l'
200 {'folder': 'inbox', 'spam_score': 0.8258, 'threshold': 0.99, 'model_version': 'spam-nb-2'} <- 'members offer: 20% off this week. free s'
200 {'folder': 'inbox', 'spam_score': 0.0, 'threshold': 0.99, 'model_version': 'spam-nb-2'} <- 'can we move the budget review to friday'
422 String should have at least 1 character <- ''

The disguised phishing email goes to spam with a score of 1.0, the newsletter stays in the inbox although its score is 0.8258 (below the strict threshold of 0.99), the work email scores 0.0, and the empty body is rejected with a 422 before the model sees it. Logging model_version and threshold with every verdict is what lets you answer "why was this email in my spam folder?" a month later.

Extensions

  • Headers and sender reputation: SPF/DKIM results, a never-seen sender, links whose text and target differ. These are the signals that catch the harmless-looking spam.
  • A review band: send scores between, say, 0.9 and the threshold to a "promotions" tab instead of a binary choice, and measure how many emails land there.
  • A transformer: fine-tune the small BERT of fine-tuning for classification and compare recall at precision 0.99 with this baseline; it must beat it by enough to pay for its latency.
  • Monitoring: track the share of flagged mail and the share of unknown tokens per day; a jump in unknown tokens was the first sign of the month-6 attack (monitoring).
  • User feedback as labels: "not spam" clicks are the most valuable labels (each is a false positive) but they are noisy and can be gamed; see label quality.

Write-up template

This run Yours
Data and labels 3,000 / 1,000 / 1,000 emails by month; training labels 3 % noisy
Target fixed in advance precision at least 0.99, recall at least 0.75
Baselines (month 4) keyword rule P 0.490 / R 0.795; NB recall at P 0.99: 0.812
Chosen model, threshold NB alpha 0.1, word 1-2 grams, t = 0.996
Test (month 5, once) P 0.996, R 0.781, 1 of 648 real emails flagged
After the attack (month 7, once) normalise + words: P 1.000, R 0.793
Largest remaining error harmless-looking spam, recall 0.043
Risks normaliser only knows seen tricks; few false positives behind the precision

Practice

  1. In Step 2, the winning model was chosen by recall at precision 0.99 on month 4. Why not choose it by PR-AUC instead?
Answer

PR-AUC averages precision over all recall levels, including thresholds the product will never use (precision 0.6, 0.8). Two models can have the same PR-AUC and very different recall at the one point that matters. Here naive Bayes and logistic regression have similar PR-AUC (0.958 and 0.953 in Step 1) and different recall at precision 0.99 depending on C (0.807 for C=1, 0.665 for C=100 in Step 2). Choose by the metric that matches the decision.

  1. Change the generator so that ham never contains promo sentences: MIX[0] = (["work", "chat", "notice"], [0.5, 0.3, 0.2]). Predict what happens to recall at precision 0.99, then run Step 1.
Answer

Recall at precision 0.99 jumps from 0.812 to 0.943 for naive Bayes, and the keyword rule's precision from 0.490 to 0.755. Without newsletters, any offer or prize draw means spam, so even the harmless-looking spam built from promo sentences becomes easy; only spam made of work or chat sentences is left. The difficulty of the problem lives in its hard negatives: a corpus without the newsletters would produce an optimistic filter that fails in real inboxes, where newsletters are common.

  1. A colleague proposes to pick the month-7 threshold on month 7 itself "because it is the most recent data". What is wrong, and what should be done instead?
Answer

Month 7 is the test set of the fix; choosing the threshold on it makes the reported precision and recall optimistic (the threshold is fitted to exactly those emails). Choose on month 6, report month 7 once. When month 8 arrives, month 7 may become validation data for the next retraining and threshold, and month 8 its test.

Test yourself

Why is the filter's threshold 0.996 rather than 0.5?

  1. Naive Bayes always needs a threshold of 0.996
  2. It was chosen on month 4 as the lowest threshold with precision at least 0.99, and naive Bayes scores are extreme
  3. It was chosen on the test month to reach precision 0.996
  4. A higher threshold always gives higher recall

On month 6 the launched model's recall fell from 0.781 to 0.647 while precision stayed high. Why did precision not suffer?

  1. The disguises removed spam evidence; they did not add spam evidence to real emails
  2. Month 6 had no real emails
  3. The threshold was lowered
  4. Character n-grams were used

Which split protects against copies of the same spam campaign appearing in training and test data?

  1. A random 80/20 split
  2. A stratified random split
  3. A split by month
  4. Five-fold cross-validation with shuffling

70 harmless-looking spams in month 7 were found with recall 0.043. What is the best next step?

  1. Lower the threshold until they are caught
  2. Add signals outside the text, such as sender reputation and header checks
  3. Train longer
  4. Remove them from the test set