Phishing Email Detector (TF-IDF + red flags)

A small, explainable phishing classifier for email text. Paste an email (headers optional) and it returns the probability that it's phishing, plus the specific red flags behind the score: lookalike sender domains, mismatched Reply-To, links to raw IPs or free hosting, requests for passwords, codes, gift cards or wire transfers, pressure and secrecy language.

It is a logistic regression over three feature blocks, small enough (about 1 MB of weights) to run entirely in the browser. Try it in the Phishing Email Detector Space.

block features
words TF-IDF of word unigrams + bigrams (15k terms)
characters TF-IDF of character 3-5-grams within word boundaries (25k terms), which catches n0rthwind, -secure-login, .top
red flags 24 binary, rule-based checks on the sender, the links and the request (list below)

Quick start

from huggingface_hub import hf_hub_download
from skops.io import load, get_untrusted_types
import sys, os

repo = "DaveyD347/phishing-email-tfidf-redflags"
files = ["model.skops", "src/redflags.py", "src/redflags_spec.json", "src/train.py"]
paths = [hf_hub_download(repo, f) for f in files]
sys.path.insert(0, os.path.dirname(paths[1]))
from train import featurize          # the same preprocessing used in training
from redflags import analyze

m = load(paths[0], trusted=get_untrusted_types(file=paths[0]))

email = """From: Bluegate Bank Security <security@bluegate-bank-verify.top>
Subject: Your online banking has been suspended

Dear Customer, verify your identity and confirm your card number and PIN within 24 hours:
http://bluegate-bank-verify.top/secure/login"""

X = featurize(m["word"], m["char"], [email], m["flag_scale"])
p = m["clf"].predict_proba(X)[0, 1]
print(f"P(phishing) = {p:.3f}, phishing = {p >= m['threshold']}")
for f in analyze(email)["flags"]:
    print("-", f["label"])

Check what get_untrusted_types returns before loading any .skops file you didn't create. For JavaScript, model.json holds the same weights; space/model.js and space/redflags.js in the Space reproduce the pipeline (a parity test checks JS and Python agree to within 1e-5 on 1,246 emails).

Evaluation

Trained on the train + validation splits of DaveyD347/synthetic-phishing-emails. The test split uses templates the model never saw, and the challenge set is 40 emails written by hand.

set threshold accuracy precision recall macro F1 ROC AUC false-positive rate
test (3,600, unseen templates) 0.35 0.958 0.999 0.906 0.957 0.995 0.05%
test, at 0.5 0.50 0.921 1.000 0.823 0.918 0.995 0.00%
challenge (40, hand-written) 0.35 0.975 1.000 0.950 0.975 1.000 0.00%

Confusion matrix

Per family on the test split: tax-refund lures 99%, link-free business email compromise (wire requests, payroll diversion, thread hijacking) 88%, legitimate workplace, IT and personal mail 99.8-100%. The one challenge miss is a casual, lowercase "did you see the folder I sent? log in with your work email" message from an unknown sender with no headers, the kind of lure that relies on context the text alone doesn't carry.

Hard negatives that a naive keyword model flags, scored by this model: a real password-expiry reminder (0.1%), "Your payment method was declined" from the shop's own domain (4.8%), "Your account is locked" after failed logins (0.4%), a payroll "direct deposit change confirmed" notice (0.9%).

How it was trained

  • C (inverse regularization) and the red-flag weight were picked by 5-fold grouped cross-validation over templates (each fold scores templates left out of training). Best: C=30, flag_scale=0.5, macro F1 0.925 Β± 0.054 across folds.
  • The decision threshold (0.35) maximizes macro F1 on the out-of-fold predictions (0.934 vs 0.927 at 0.5).
  • The dataset's fictional .example domains are rewritten to .com before the text features see them, so the model cannot learn ".example means legitimate".
  • Class weights are balanced. Training takes about 3.5 minutes on a laptop CPU, including the cross-validation.

Red flags

id what it checks severity
credential_request asks to verify identity, confirm a password, card number, PIN, SSN, or sign in with work credentials high
code_request asks you to reply with or read out a one-time code high
payment_request wire transfer, changed bank details, direct deposit update, "processing fee" high
gift_cards gift cards, "scratch off the back", photos of the codes high
prize_money winnings, inheritance, next of kin, airdrops, guaranteed returns high
crypto_secret recovery or seed phrase, "connect your wallet" high
macro_attachment .zip/.iso/.html/.xlsm/... attachments, "enable content", password-protected files high
url_ip link to a raw IP address high
url_lookalike digits for letters, brand-plus-"secure/login/verify" domains, a domain hidden in a subdomain high
reply_to_mismatch Reply-To on a different domain than From high
sender_lookalike deceptive or cheap-TLD sender domain high
urgency within N hours, immediately, final notice, last chance medium
threat suspended, locked, permanently closed, returned to sender medium
secrecy confidential, keep this between us, can't talk, email only medium
callback "call this number to cancel the charge" medium
job_mule deposit-and-forward jobs, weekly pay for no experience medium
url_shortener bit.ly, tinyurl and similar medium
url_risky_tld .top, .xyz, .click, .online, ... medium
url_free_hosting web.app, pages.dev, netlify.app, weebly.com, ... medium
url_sender_mismatch link domain differs from the sender's domain medium
display_name_brand display name claims an organization ("IT Help Desk", "Bank Security") the address doesn't match medium
generic_greeting Dear Customer / User / Sir or Madam low
url_http unencrypted http:// link low
from_freemail sent from free webmail low

The model learns how much each flag matters. None of them decides the verdict alone: legitimate mail trips flags too (a sale that "ends tonight", a real "account locked" notice), and the wording features pull those back down.

Intended use

  • Teaching and demos: show why an email looks like phishing, flag by flag and word by word.
  • A cheap first-pass triage signal (for example, ranking user-reported emails for a SOC queue) alongside real mail-security controls.

Not a replacement for a secure email gateway. It never sees authentication results (SPF, DKIM, DMARC), the real destination of links, sender reputation, or attachment contents.

Limitations and risks

  • Trained only on synthetic data about fictional companies. Expect lower accuracy on real mail, especially HTML-heavy marketing, non-English mail, and novel lure types.
  • Rule features are public. An attacker who reads this card can write around them (plain https links on a clean-looking domain, no urgency words). The text features help, but a careful, personalized spear-phish can pass.
  • Bias toward the dataset's styles. Unusual but legitimate mail (terse IT notices from personal addresses, real prize notifications) can be flagged; short, context-dependent lures can slip through.
  • Probabilities are only roughly calibrated; use them for ranking, not as exact risk estimates.

Files

file what
model.skops scikit-learn vectorizers + logistic regression, plus flag_scale and threshold
model.json the same weights for JavaScript (format: tfidf-logreg-v1)
config.json hyper-parameters, the CV grid and scores
eval/metrics.json, eval/confusion_matrix.png evaluation results
src/ training, evaluation, red-flag and export code

License

Apache 2.0.

Downloads last month
-
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support

Dataset used to train DaveyD347/phishing-email-tfidf-redflags

Spaces using DaveyD347/phishing-email-tfidf-redflags 2

Evaluation results