Lesson 12 · 55 minutes
Build a phishing text classifier
- Build, train and measure a text classifier with a Pipeline
- Test it on your own messages and read which words it relies on
- Save the model with its hash, say why an untrusted file is dangerous, and write a model card
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 wants a first filter that scores each incoming message for phishing, so that analysts read the worst ones first. They have 40 labelled messages and no time. As lesson 10 asks, each text appears once with one label. You build the filter with the whole course: data, split, features, model, measures. Then you add eight messages, measure again with a method for small data, and check whether the weak spot is closed.
Recall
In lesson 9, what does TfidfVectorizer give for each text, and what is its main limit?
One number for each word of the vocabulary. A word that is frequent in the text and rare in the others scores high. Its limit: it knows only the words in your data, so "stole" and "stolen" are different words.
In lesson 3, why must the test set stay out of every decision?
If test data influences training, the score is too good (data leakage). Only a test part that the model never saw says how it works on new data.
The idea
A Pipeline chains steps into one object. First TfidfVectorizer turns text into vectors (lesson 9). Then LogisticRegression learns from them (lesson 3). One fit trains both.
- Message → TfidfVectorizer: text becomes word weights
- TfidfVectorizer → LogisticRegression: weights become a chance
- LogisticRegression → Verdict: above 0.5 means phishing
joblib saves a model to a file in Python's pickle format. Loading a pickle can run any code that its author put inside. Treat a model file like a program.
Worked example
1. Write the labelled messages
Create messages.py in the lab folder. A Python file can be imported by another one, so that the data lives in one place. These 40 messages are invented: 20 phishing-like (1) and 20 normal (0). Each item is a pair: the label and the text.
messages.py
# (label, text): 1 = phishing-like, 0 = normal
DATA = [
(1, "Account locked. Verify your password at the link"),
(1, "Urgent: confirm your bank details or lose access"),
(1, "You won a prize. Click here to claim it"),
(1, "Security alert: unusual sign in. Log in at this link"),
(1, "Your parcel is held. Pay a small fee at the link"),
(1, "Payment failed. Update your card details now"),
(1, "Your mailbox is full. Click to verify your login"),
(1, "Your password expires today. Confirm it at the link"),
(1, "Virus found. Call this number and give us access"),
(1, "Free gift card. Enter your password to continue"),
(1, "Invoice overdue. Open the file and enter your login"),
(1, "Account suspended. Verify your identity now"),
(1, "You are selected. Send your bank details to get money"),
(1, "Your tax refund is ready. Confirm your card number"),
(1, "Reset your password using this link immediately"),
(1, "Unusual activity. Verify your account in 12 hours"),
(1, "Win a free phone. Click now and enter your details"),
(1, "Delivery failed. Pay the fee at this link"),
(1, "Your email will be deleted. Log in now"),
(1, "Your account was hacked. Click here to secure it"),
(0, "Lunch at noon? I booked a table for four"),
(0, "The meeting moved to Thursday at ten"),
(0, "The minutes of the call are in the shared folder"),
(0, "Can you review my pull request today?"),
(0, "Happy birthday! The team has a cake at three"),
(0, "The build passed and the release is on Friday"),
(0, "The quarterly report is due next Monday"),
(0, "I will be late because my train was delayed"),
(0, "Thanks for the notes, they helped"),
(0, "Could you send me the slides before the workshop?"),
(0, "The office will be closed on the public holiday"),
(0, "Here is the agenda for tomorrow's session"),
(0, "Want to join the football game after work?"),
(0, "The printer on the second floor works again"),
(0, "I updated the test plan, please take a look"),
(0, "See you at the conference next week"),
(0, "The new starter begins on Monday"),
(0, "Your order has shipped and arrives on Wednesday"),
(0, "We moved the server maintenance to Sunday night"),
(0, "Great talk today, I liked the logging part"),
]2. Write the pipeline
Create phish.py. It trains the Pipeline, prints a report, the wrong answers and the top words, tries new messages, then saves and loads the model. New parts, in the order of the code:
from messages import DATAloads the list that you wrote in step 1.- A list comprehension,
[label for label, text in DATA], builds a new list from an old one in one line. Pipeline([...])takes a list of named steps.lowercase=Trueturns every text to lower case first.ngram_range=(1, 2)makes the vectoriser count single words and pairs of words.C=10lets the model fit the data more closely than the default does.zip(a, b)walks through two lists at the same time.model.predict_proba(tests)[:, 1]takes the second column of every row: the chance of label 1 for each message.order[::-1]reverses a list, and[:6]keeps its first six items, soorder[::-1][:6]is the six largest weights..all()is true only if every item is true.model["tfidf"]andmodel["clf"]pick one step out of the Pipeline by its name..argsort()gives the positions of the weights from the smallest to the largest.target_names=["normal", "phishing"]puts a name on the classes 0 and 1 in the report.joblib.dump(model, file)writes the model to a file, andjoblib.load(file)reads it back.
phish.py
import joblib
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from messages import DATA
labels = [label for label, text in DATA]
texts = [text for label, text in DATA]
print("messages:", len(texts), " phishing:", sum(labels))
X_train, X_test, y_train, y_test = train_test_split(
texts, labels, test_size=0.25, random_state=42, stratify=labels
)
print("train:", len(X_train), "test:", len(X_test))
model = Pipeline([
("tfidf", TfidfVectorizer(lowercase=True, ngram_range=(1, 2))),
("clf", LogisticRegression(C=10, max_iter=1000)),
])
model.fit(X_train, y_train)
pred = model.predict(X_test)
print(classification_report(y_test, pred, target_names=["normal", "phishing"], digits=3))
for text, truth, guess in zip(X_test, y_test, pred):
if truth != guess:
print("wrong:", text)
words = model["tfidf"].get_feature_names_out()
weights = model["clf"].coef_[0]
order = weights.argsort()
print("pushes to phishing:", [words[i] for i in order[::-1][:6]])
print("pushes to normal: ", [words[i] for i in order[:6]])
tests = [
"Verify your password at this link or your account will be closed",
"Can we move the review to Thursday?",
"Your parcel is waiting, confirm your card details",
"The release notes are in the shared folder",
"Dear user, kindly update billing information via the attached form",
]
for text, chance in zip(tests, model.predict_proba(tests)[:, 1]):
print(f"{chance:.2f} {text}")
joblib.dump(model, "phish.joblib")
loaded = joblib.load("phish.joblib")
print("same answers after loading:", (loaded.predict(X_test) == pred).all())3. Run it
cd ~/krlab/how-ai-works
source .venv/bin/activate
python phish.pymessages: 40 phishing: 20
train: 30 test: 10
precision recall f1-score support
normal 1.000 0.800 0.889 5
phishing 0.833 1.000 0.909 5
accuracy 0.900 10
wrong: I will be late because my train was delayed
pushes to phishing: ['your', 'link', 'click', 'it', 'your password', 'password']
pushes to normal: ['the', 'on', 'for', 'moved', 'has', 'conference']
0.92 Verify your password at this link or your account will be closed
0.21 Can we move the review to Thursday?
0.89 Your parcel is waiting, confirm your card details
0.18 The release notes are in the shared folder
0.32 Dear user, kindly update billing information via the attached form
same answers after loading: True4. Read the result with care
The last two lines of the report (the macro and weighted averages) are left out of the output above. Ten test messages is a tiny test: one mistake moves every number by ten points. The mistake is a false alarm. It lowers the precision of the phishing class (0.833) and the recall of the normal class (0.800).
The weights show the shortcut. "your", "link" and "click" push towards phishing, and "the", "for" and "on" push towards normal. Some are habits of the writer, not signs of fraud. The last test message is phishing in new words, and the model gives it 0.32, so it calls it normal. Add messages of your own to tests and look for gaps.
5. Save and load safely
The last lines wrote phish.joblib and read it back with the same answers. The security fact: joblib.load can run code from the file. Load only files that you made, or that you got from a trusted source and checked with a hash.
sha256sum (lesson 11) prints a fingerprint of a file, and -c checks a saved one. Save the fingerprint now, and check the file against it before you load it.
sha256sum phish.joblib > phish.sha256
sha256sum -c phish.sha256phish.joblib: OK- Attacker → phish.joblib: replaces it with a file that holds code
- Attacker → phish.sha256: can replace the fingerprint too
- sha256sum → phish.sha256: reads the saved fingerprint
- sha256sum → phish.joblib: compares the file with it
- phish.joblib → joblib.load: its code runs at load time
-c compares the saved fingerprint with the file as it is now. A line that ends in FAILED means that the file changed: do not load it. The fingerprint proves only that the file is as it was when the fingerprint was made. Keep it somewhere else, or get it from the author by a different route. An attacker who can replace the model in this folder can replace the fingerprint next to it, and then OK proves nothing.
6. Write the model card
A model card is a one-page note on what a model is for, what it learned from, how it scored, where it fails and which file it is. model_card.py loads phish.joblib and writes model-card.txt. platform.python_version() gives the Python version and sklearn.__version__ the library version. Text between triple quotes can span lines, and {...} parts are filled in. cross_val_score(model, texts, labels, cv=5) cuts the data into five parts (folds), trains five times with one part left out each time, and returns five scores. The hash code is from lesson 11.
model_card.py
import hashlib
import platform
import joblib
import sklearn
from sklearn.metrics import classification_report
from sklearn.model_selection import cross_val_score, train_test_split
from messages import DATA
labels = [label for label, text in DATA]
texts = [text for label, text in DATA]
X_train, X_test, y_train, y_test = train_test_split(
texts, labels, test_size=0.25, random_state=42, stratify=labels
)
model = joblib.load("phish.joblib")
pred = model.predict(X_test)
report = classification_report(y_test, pred, target_names=["normal", "phishing"], digits=3)
wrong = [text for text, truth, guess in zip(X_test, y_test, pred) if truth != guess]
dear = "Dear user, kindly update billing information via the attached form"
digest = hashlib.sha256(open("phish.joblib", "rb").read()).hexdigest()
card = f"""Model card: phishing text filter
Data: {len(texts)} invented messages, {len(X_train)} to train, {len(X_test)} to test, seed 42
Versions: python {platform.python_version()}, scikit-learn {sklearn.__version__}
Test report:
{report.rstrip()}
Cross-validation, 5 folds: mean {cross_val_score(model, texts, labels, cv=5).mean():.3f}
Wrong on the test part: {wrong}
Chance of phishing for the "Dear user" message: {model.predict_proba([dear])[0][1]:.2f}
Model file: phish.joblib, sha256 {digest}"""
with open("model-card.txt", "w") as f:
f.write(card + "\n")
print(card)python model_card.pyModel card: phishing text filter
Data: 40 invented messages, 30 to train, 10 to test, seed 42
Versions: python 3.14.4, scikit-learn 1.9.1
Test report:
precision recall f1-score support
normal 1.000 0.800 0.889 5
phishing 0.833 1.000 0.909 5
accuracy 0.900 10
macro avg 0.917 0.900 0.899 10
weighted avg 0.917 0.900 0.899 10
Cross-validation, 5 folds: mean 0.975
Wrong on the test part: ['I will be late because my train was delayed']
Chance of phishing for the "Dear user" message: 0.32
Model file: phish.joblib, sha256 e086e5ea40cf504c1bf9bca66954768b812ebff0f1e3c51f3f834c15aed983a5Your hash can differ from this one. The card records yours. Keep the card: it shows a reader the data, the seed, the versions, the scores, the misses and the model file.
Your turn
The last test message of the worked example, "Dear user, kindly update billing information via the attached form", slipped through at 0.32. Try to close the gap with more data, and measure the result. There is no code here: adapt phish.py.
Add these eight messages at the end of DATA, in the order of the table, so that it holds 48. The new phishing text uses other words than the "Dear user" message on purpose: a near copy would show only that the model remembers it.
| Label | Text |
|---|---|
| 1 | Your streaming account is on hold. Update your payment details here |
| 1 | Final notice. Verify your login or your account will be closed |
| 1 | Congratulations, you are our lucky winner. Claim your reward at the link |
| 1 | Please update your invoice details through the form that we attached |
| 0 | The backup job finished without errors last night |
| 0 | Can we move our one to one to Friday morning? |
| 0 | Please find the training schedule for next month attached |
| 0 | Thanks for fixing the bug so quickly |
- Split the 48 messages with
test_size=0.3,random_state=3andstratify=labels. Train the same Pipeline on the training part. Score it on the test part. - With ten or fifteen test messages, one split is a weak proof. Use
cross_val_score(model, texts, labels, cv=5)fromsklearn.model_selection. It trains five times, each time with a different fifth of the data left out, and returns five scores (lesson 7). Take their mean. - Train a new Pipeline on all 48 messages. Ask it for the phishing chance of the "Dear user" message.
Last, write two sentences for the mail team: what the new messages changed (compare the chance with 0.32), and why the filter still needs tests with new wording.
Check yourself
Why is the vectoriser inside the Pipeline and not run before the split?
Fitted on all messages, it would pass test information into training (data leakage). Inside the Pipeline it sees only the training messages.
Why can loading a model file run code?
Pickle rebuilds Python objects by calling functions. A file made by an attacker can call one that runs a command when you load it, before any prediction.
The model gives a phishing message 0.32. How do you improve it?
Add varied phishing examples in this style, then split and measure again. Moving the cut-off teaches no new words.
Field notes
- Check a model file like software you install: store a SHA-256 hash when you save it, compare before you load it, and let only your build write to the folder. Formats that do not run Python code when you load them, such as safetensors and ONNX, remove this particular risk. Still check where the file came from.
- With 40 messages, use cross-validation. The card's mean of 0.975 is four folds of 1.0 and one of 0.88. A fold holds 8 messages, so one mistake moves it by 12 points. A real filter needs thousands of messages.
- Phishing text changes. Measure the model on a labelled sample of recent mail every month, and retrain when recall falls.
- Attackers change single words until the score falls below the cut-off. This is an evasion attack, and the attack courses use this model. Keep
phish.py.