Lesson 05 · 45 minutes
Classify suspicious messages and test the model on new wording
- Train a text classifier on messages and add a domain feature that does not depend on wording
- Measure precision and recall on messages in the old style and in a new style
- Explain why a shift in the data lowers recall, and what a defender can do about it
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
The mail team has a filter that works well on the phishing of last year. This quarter, users report messages that read like normal office mail: calm, polite, with no threat and no deadline. The filter lets many of them through. Your lead asks: "Is the model broken, or is the data different? Measure it. Then tell me what we change." You have 600 labelled messages of the old style, and 200 labelled messages of the new style that the model has never seen. All messages are short, invented records. Their wording is plain on purpose: they are test data for a detector.
Recall
Lesson 2: the model has a recall of 0.71 at the cut-off 0.5. What does that cost?
29 percent of the real incidents are below the cut-off. If you close those alerts with no reading, they are missed in silence.
"How AI works", lesson 9: how does `TfidfVectorizer` turn a message into numbers?
It gives one number for each word of the vocabulary. A word that is common in the message and rare in the others scores high. A word that the model never saw in training has no column and counts for nothing.
The idea
A text classifier learns from words. It learns that "verify", "urgent" and "suspended" often come with phishing. This works until the attackers change their words. A change in the data after you trained the model is data shift. A model does not warn you about it: it still gives a score for every message, and the scores are wrong.
A defender has a second kind of evidence: facts about the message that do not depend on its words. The lesson adds three numbers to the text. One of them depends on wording, and it stays as a control, so that you can see that it carries nothing when the wording changes.
| Feature | Meaning | Weakness |
|---|---|---|
| Urgent words (the control) | Count of words such as "urgent", "now", "verify". It depends on wording. | Disappears when the writer is calm |
| Has a link | The message holds a link | Real mail has links too |
| Domain mismatch | The link points to a domain that is not the sender's (or a sub-domain of it) | A hijacked real account has a matching domain. Real marketing mail can use a mail service. |
A look-alike domain is a domain that the attacker owns and that is not the sender's.
- Attacker → Look-alike domain: the link goes to a site it owns
- Attacker → Message: calm wording, nothing urgent
- Message → Classifier: the words, the sender and the link domain
- Classifier → Recipient: deliver, or hold for a person
The test of the lesson is to train on the old style once, and measure on both styles, with and without the three numbers.
Worked example
1. Look at the messages
messages(seed, n, style) returns short labelled records with the claimed sender domain, the link domain (empty if there is no link) and the text. Style "new" is wording that the model never saw in training.
python3 -c "
from gen import messages
for style, seed in (('old', 1), ('new', 3)):
for m in messages(seed, 40, style)[:5]:
print(style, m['label'], m['sender'].ljust(13), (m['link'] or '-').ljust(18), m['text'][:58])
"old 1 bank.example verify-now.test Your document is waiting for you at the link
old 0 shop.example - Lunch at noon? I booked a table for four
old 0 cloud.example - Lunch at noon? I booked a table for four
old 1 shop.example shop.example URGENT: your account is suspended. Verify your password no
old 1 cloud.example account-check.test Your document is waiting for you at the link
new 1 cloud.example update-portal.test Your colleague sent you a file for review. Open it at the
new 0 cloud.example cloud.example A document was shared with you. You can open it here
new 0 post.example post.example The report you asked for is ready. You can read it at the
new 1 post.example verify-now.test A voice message was left for you. Listen at the link
new 0 shop.example mailer.test Your colleague sent you a file for review. Open it at the In the old style, most phishing text is urgent. In the new style, the same sentence appears with label 1 and with label 0. The text cannot tell them apart, and only the link can.
2. Save the classifier
Save phish.py. extra(m) returns three numbers for a message: how many urgent words (whole words, with \b and rf as in lesson 3) it holds, whether it has a link, and whether the link domain is foreign. hstack joins two tables of numbers side by side, and csr_matrix makes a table in the compact form (a sparse matrix) that TF-IDF also uses. LogisticRegression is the model of lesson 3 of "How AI works". build(train, use_extra) trains it and returns a function that predicts new messages. measure returns precision and recall rounded to two decimals.
phish.py
"""phish.py: a text classifier for messages, with and without three hand-made numbers."""
import re
from scipy.sparse import csr_matrix, hstack
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_score, recall_score
from gen import URGENT, messages
def extra(m):
"""Three numbers: urgent words, has a link, and the link domain does not belong to the sender."""
low = m["text"].lower()
has_link = bool(m["link"])
mismatch = has_link and m["link"] != m["sender"] and not m["link"].endswith("." + m["sender"])
return [sum(bool(re.search(rf"\b{word}\b", low)) for word in URGENT), int(has_link), int(mismatch)]
def build(train, use_extra):
"""Train and return a function that predicts a list of messages."""
vec = TfidfVectorizer()
texts = vec.fit_transform([m["text"] for m in train])
if use_extra:
texts = hstack([texts, csr_matrix([extra(m) for m in train])])
clf = LogisticRegression(max_iter=1000).fit(texts, [m["label"] for m in train])
def predict(rows):
X = vec.transform([m["text"] for m in rows])
if use_extra:
X = hstack([X, csr_matrix([extra(m) for m in rows])])
return clf.predict(X)
return predict
def measure(predict, rows):
y, p = [m["label"] for m in rows], predict(rows)
return round(precision_score(y, p, zero_division=0), 2), round(recall_score(y, p), 2)
if __name__ == "__main__":
train, test, new = messages(1, 600), messages(2, 300), messages(3, 200, "new")
print("share of phishing: train", round(sum(m["label"] for m in train) / 600, 2), " new style", round(sum(m["label"] for m in new) / 200, 2))
print(f"{'model':24}{'data':>10}{'precision':>11}{'recall':>8}")
for name, use in (("text only", False), ("text + three numbers", True)):
predict = build(train, use)
for data, rows in (("same style", test), ("new style", new)):
p, r = measure(predict, rows)
print(f"{name:24}{data:>10}{p:>11}{r:>8}")python3 phish.pyshare of phishing: train 0.32 new style 0.33
model data precision recall
text only same style 0.89 1.0
text only new style 0.31 0.52
text + three numbers same style 0.98 0.91
text + three numbers new style 0.84 0.913. Read the shift
The text-only model is good on the old style: precision 0.89 and recall 1.00. On the new style the recall falls to 0.52, and the precision falls to 0.31. Half of the phishing passes, and the model also raises alarms on many normal messages, because the same sentences appear with both labels. This is a data shift, measured. The model has not changed. The attackers' words have.
4. Add the evidence that does not need words
With the three extra numbers, the same classifier reaches precision 0.84 and recall 0.91 on the new style, and 0.98 and 0.91 on the old style. The domain number carries the load: a message that links to a foreign domain is suspicious whatever it says.
Look at the cost on the old style. The recall is 0.91, lower than the 1.00 of the text-only model. The reason is the 7 percent of phishing in the data that comes from a hijacked account and links to the sender's own domain. The text-only model caught them by their words, and the feature model trusts the matching domain a little. No single feature is enough. This is why a filter has many signals, and why you measure on data of both kinds.
5. See the feature on one message
python3 -c "
from gen import messages
from phish import extra
for m in messages(3, 40, 'new')[:4]:
print(m['label'], m['sender'], m['link'] or '-', extra(m))
"1 cloud.example update-portal.test [0, 1, 1]
0 cloud.example cloud.example [0, 1, 0]
0 post.example post.example [0, 1, 0]
1 post.example verify-now.test [0, 1, 1]The three numbers are the urgent words, the link, and the mismatch. In the new style the first is 0 for every message: it carries nothing there, and the last separates the labels.
Your turn
A third set of messages arrives: messages(4, 200, "new"). Use the training data messages(1, 600) and the functions of phish.py. You write the script. Measure both models on the new set, and count the harmless messages that have a domain mismatch.
Last, write one sentence for the mail team: which model do you run, and what do you tell users about the 7 harmless messages with a foreign link?
Check yourself
Recall fell from 1.00 to 0.52 and the model did not change. How can that be?
The data changed. The model learned old wording, and new messages use other words. Its scores are still numbers between 0 and 1, so nothing warns you. Only a measure on new labelled data shows the fall.
Why is "domain mismatch" a better feature than "number of urgent words" when attackers change?
An attacker must link to a place that they control, and that place is not the domain of the sender that they pretend to be, unless the attacker also owns a look-alike sender domain. That is why SPF, DKIM and DMARC and the age of the domain are the next signals. The urgent words are a style choice that the attacker can drop at no cost. A feature that the attacker cannot change without losing the goal lasts longer.
Seven harmless messages in the set have a mismatch. What do you do about them?
Do not drop the feature. Add context: a list of mail services that real senders use (for example the tracking domain of a known newsletter). Each entry is a decision that a person made, so the list is a control, and you review it.
You have no labels for the new wave. How can you still see a shift?
Watch what you can count with no label: the share of messages the model calls phishing, the length of the messages, the share of messages with a link. A sudden change in one of them is a sign that the data has shifted, and a reason to label a sample.
Field notes
- Measure on a sample of the newest mail every week. A model that was good in January is not good in July by default.
- Sender checks sit in the mail system: SPF (RFC 7208), DKIM (RFC 6376) and DMARC (RFC 9989, May 2026, which replaced RFC 7489) say whether a message may claim its domain. SPF lists the servers that may send for a domain, DKIM signs the message, and DMARC says what to do when neither matches the visible sender. Take the current text from the IETF. A feature from these results is stronger than anything in the body.
- MITRE ATT&CK lists phishing as technique T1566 (initial access). Take the current text from MITRE to see its sub-techniques, and use them to name what your filter covers.
- Retraining on the new wording fixes the model for a while, and the attackers can change again. Use retraining for the words and fixed checks for the facts.
- A false alarm on a real mail costs a user, and a miss costs the company. Put the threshold where your risk rule says (lesson 2), and let a person release quarantined mail.