Text Spam Detector: Naive Bayes Classifier with F1 Score
Arrays & HashingAuto-graded · 18 test casesLast updated
Tests understanding of probabilistic text classification by implementing a Multinomial Naive Bayes model from scratch and evaluating it with the F1 score.
Text Spam Detector: Naive Bayes Classifier with F1 Score
You will implement a Multinomial Naive Bayes text classifier for binary spam detection — no ML libraries allowed. The classifier is trained on labeled messages, then evaluated on a separate test set using the F1 score for the positive class ("spam").
Background
Naive Bayes assigns a class to a document by computing the log-probability of each class and picking the higher one. For a document with token counts $x_w$, the score for class $c$ is:
$$ \log P(c \mid x) \propto \log P(c) + \sum_{w} x_w \cdot \log P(w \mid c) $$
To avoid zero probabilities for unseen words, apply Laplace/Lidstone smoothing with parameter $\alpha$:
$$ P(w \mid c) = \frac{\text{count}(w, c) + \alpha}{\text{total_tokens}(c) + \alpha \cdot |V|} $$
where $|V|$ is the size of the vocabulary built from the training set only.
Only tokens matching the pattern [a-z0-9]+ (after lowercasing) are used. Tokens in a test document that do not appear in the training vocabulary are ignored during scoring.
Task
Implement text_spam_classifier which:
- Builds a vocabulary and per-class token counts from
train_textsandtrain_labels. - Computes log-prior probabilities from the training label distribution.
- Classifies each message in
test_textsusing the smoothed log-probability scores described above. - On an exact tie between the two class scores, predicts
"spam". - Computes and returns the F1 score for the positive class (
"spam") across all test predictions.
Input / Output
Parameters:
train_texts— list of strings, the training messagestrain_labels— list of strings, one per training message; each value is either"spam"or"not_spam"test_texts— list of strings, the messages to classifytest_labels— list of strings, the ground-truth labels for the test messagesalpha— positive float, the Laplace smoothing parameter
Returns a dict with exactly two keys:
"predictions"— alist[str]of predicted labels ("spam"or"not_spam") in the same order astest_texts"f1"— afloat, the F1 score for the"spam"class on the test set (0.0 when the denominator is zero)
F1 Score Definition
$$ F1 = \frac{2 \cdot TP}{2 \cdot TP + FP + FN} $$
where TP, FP, and FN are counted with respect to the "spam" class. If $2 \cdot TP + FP + FN = 0$, return f1 = 0.0.
Constraints
1 ≤ len(train_texts) == len(train_labels)1 ≤ len(test_texts) == len(test_labels)- Every label in both lists is either
"spam"or"not_spam" alpha > 0- Messages may be empty strings; an empty message contributes no tokens
- Vocabulary is built from training data only — test tokens outside the vocabulary are skipped
- Do not use any external ML libraries (e.g., scikit-learn, nltk); use only the Python standard library
Examples
Example 1
Input: text_spam_classifier(['Win a free iPhone now! Click this link', 'Meeting moved to tomorrow at 10am', 'Congratulations, you won a cash prize', 'Please review the attached project report', 'Limited offer buy cheap medication today', 'Can you send me the dinner recipe?'], ['spam', 'not_spam', 'spam', 'not_spam', 'spam', 'not_spam'], ['free cash prize click now', 'project meeting tomorrow', 'cheap offer medication', 'send the report please'], ['spam', 'not_spam', 'spam', 'not_spam'], 1)
Output: {'predictions': ['spam', 'not_spam', 'spam', 'not_spam'], 'f1': 1}
Example 2
Input: text_spam_classifier(['urgent winner claim your reward', 'team lunch is scheduled Friday', 'buy now and get a free bonus', 'the deployment completed successfully', 'your account won a prize', 'please call me after work'], ['spam', 'not_spam', 'spam', 'not_spam', 'spam', 'not_spam'], ['free reward winner', 'deployment is complete', 'please call Friday', 'claim bonus now'], ['spam', 'not_spam', 'not_spam', 'spam'], 0.5)
Output: {'predictions': ['spam', 'not_spam', 'not_spam', 'spam'], 'f1': 1}
Example 3
Input: text_spam_classifier(['', 'hello friend', 'FREE!!! FREE!!! offer', 'normal project update', 'buy buy buy'], ['not_spam', 'not_spam', 'spam', 'not_spam', 'spam'], ['', 'free offer', 'project update', 'buy now'], ['not_spam', 'spam', 'not_spam', 'spam'], 1)
Output: {'predictions': ['not_spam', 'spam', 'not_spam', 'spam'], 'f1': 1}
Hints
Hint 1
Build two data structures during training: a per-class Counter of token frequencies, and a per-class total token count. The vocabulary is the union of all tokens seen in training.
Hint 2
When scoring a test document, loop over its token counts; for each token that exists in the vocabulary, add count * log((word_counts[label][token] + alpha) / (total_words[label] + alpha * vocab_size)) to the running log-score for that label. Tokens not in the vocabulary contribute nothing.
Hint 3
Compute F1 directly from TP, FP, and FN tallied over all test predictions — no library needed. Remember the tie-breaking rule: predict 'spam' when both class scores are exactly equal.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea: Multinomial Naive Bayes from scratch
The classifier scores each class by combining a log-prior (how often that class appears in training) with a sum of smoothed log-likelihoods (how often each token appears in documents of that class). Whichever class scores higher wins.
Why this works on text: word counts per document follow a multinomial distribution well enough that the independence assumption, while technically wrong, still produces a strong ranking signal.
Three things to get right:
-
Vocabulary from training only. The vocabulary is built once from
train_texts. Test-time tokens outside this set are silently skipped, which mirrors the information boundary that prevents leakage. -
Laplace smoothing. Without it, a single token absent from one class's training documents zeros out that entire class's probability. The smoothed estimate is
(count(w, c) + α) / (total_tokens(c) + α * |V|). This is computed in log-space to avoid floating-point underflow. -
Tie-breaking toward the positive class. When both log-scores are exactly equal, predicting
"spam"is the specified behavior.
Computing F1 without libraries
F1 for the positive class needs only three tallies collected in a single pass over the test predictions:
- TP: predicted spam, truly spam
- FP: predicted spam, truly not_spam
- FN: predicted not_spam, truly spam
$$F1 = \frac{2 \cdot TP}{2 \cdot TP + FP + FN}$$
If the denominator is zero (no spam predicted and none in ground truth), return 0.0.
Complexity
Let $N$ = number of training documents, $L$ = average tokens per document, $|V|$ = vocabulary size, $M$ = number of test documents.
- Training: $O(NL)$ to tokenize and count; $O(NL)$ total vocabulary insertions.
- Prediction: $O(L)$ per test document (one pass over its tokens, each lookup is $O(1)$ via hash set).
- Memory: $O(|V|)$ for the vocabulary and per-class counters; $O(|V|)$ dominant term for parameters.
Full solution
import math
import re
from collections import Counter
from typing import Dict, List
def text_spam_classifier(
train_texts: List[str],
train_labels: List[str],
test_texts: List[str],
test_labels: List[str],
alpha: float,
) -> Dict[str, object]:
token_pattern = re.compile(r"[a-z0-9]+")
def tokenize(text: str) -> List[str]:
return token_pattern.findall(text.lower())
# --- Training phase ---
class_counts = Counter(train_labels)
n_train = len(train_texts)
word_counts: Dict[str, Counter] = {"spam": Counter(), "not_spam": Counter()}
total_words: Dict[str, int] = {"spam": 0, "not_spam": 0}
vocabulary: set = set()
for text, label in zip(train_texts, train_labels):
tokens = tokenize(text)
vocabulary.update(tokens)
word_counts[label].update(tokens)
total_words[label] += len(tokens)
vocab_size = max(1, len(vocabulary))
# Log-prior for each class
log_prior: Dict[str, float] = {}
for label in ("spam", "not_spam"):
count = class_counts[label]
log_prior[label] = math.log(count / n_train) if count > 0 else float("-inf")
# --- Prediction ---
def predict(text: str) -> str:
token_counts = Counter(tokenize(text))
scores: Dict[str, float] = {}
for label in ("spam", "not_spam"):
if class_counts[label] == 0:
scores[label] = float("-inf")
continue
denominator = total_words[label] + alpha * vocab_size
score = log_prior[label]
for token, count in token_counts.items():
if token in vocabulary:
prob = (word_counts[label][token] + alpha) / denominator
score += count * math.log(prob)
scores[label] = score
# Tie-break: prefer "spam" (positive class)
return "spam" if scores["spam"] >= scores["not_spam"] else "not_spam"
predictions = [predict(text) for text in test_texts]
# --- F1 for the "spam" class ---
tp = sum(p == "spam" and y == "spam" for p, y in zip(predictions, test_labels))
fp = sum(p == "spam" and y == "not_spam" for p, y in zip(predictions, test_labels))
fn = sum(p == "not_spam" and y == "spam" for p, y in zip(predictions, test_labels))
denom = 2 * tp + fp + fn
f1 = 0.0 if denom == 0 else (2.0 * tp) / denom
return {"predictions": predictions, "f1": f1}