KatInterview

Text Spam Detector: Naive Bayes Classifier with F1 Score

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashingnaive-bayestext-classificationf1-score

Last 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:

  1. Builds a vocabulary and per-class token counts from train_texts and train_labels.
  2. Computes log-prior probabilities from the training label distribution.
  3. Classifies each message in test_texts using the smoothed log-probability scores described above.
  4. On an exact tie between the two class scores, predicts "spam".
  5. 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 messages
  • train_labels — list of strings, one per training message; each value is either "spam" or "not_spam"
  • test_texts — list of strings, the messages to classify
  • test_labels — list of strings, the ground-truth labels for the test messages
  • alpha — positive float, the Laplace smoothing parameter

Returns a dict with exactly two keys:

  • "predictions" — a list[str] of predicted labels ("spam" or "not_spam") in the same order as test_texts
  • "f1" — a float, 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.