Natural Language Processing · Intermediate level

Intermediate level · Module 4: Naive Bayes and Text Classification · Lesson 2 of 3

Spam Filtering and Model Comparison

Learners build a spam filter on the SMS Spam Collection, then compare Naive Bayes with logistic regression on TF-IDF features using cross-validation.

In this lesson you will

  • Build and evaluate a spam filter
  • Compare classifiers fairly with cross-validation

Key concepts

SMS Spam CollectionLogisticRegressioncross_val_scoreGridSearchCVF1 score

The lesson

The SMS Spam Collection (UCI repository, CC BY 4.0) contains several thousand English SMS messages labelled ham or spam. It is a standard first dataset, but it was collected outside South Sudan, so local spam (for example fake mobile-money or prize messages) may look different.

Logistic regression learns a weight per feature and often matches or beats Naive Bayes on TF-IDF features when there is enough data. Compare models with cross_val_score on the same folds and the same metric.

GridSearchCV can tune a whole pipeline, for example the vectoriser's ngram_range and the model's C or alpha, with parameter names like 'tfidfvectorizer__ngram_range'. Keep a final test set aside that is only used once.

Step by step

  1. Load the SMS Spam Collection and inspect the class balance.
  2. Cross-validate Naive Bayes and logistic regression pipelines with F1 for spam.
  3. Tune ngram_range and alpha or C with GridSearchCV.
  4. Test the best model on 30 synthetic local-style spam messages and record the failures.

Practice activity

Build, tune and test a spam filter and report its performance on local-style messages.

Expected result: A tuned model, a fair comparison and an honest report of weaknesses on local-style spam.

Check your understanding

  1. Why compare models on the same cross-validation folds?

    Show answer

    So that differences come from the models, not from different data splits.

  2. Why test on local-style spam separately?

    Show answer

    The public dataset was collected elsewhere, so local spam may differ.

Further learning

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.