In this project we build an SMS/e-mail spam classifier. We clean and explore 5,572 messages, preprocess the text with NLTK, convert it to numbers with TF-IDF and compare three Naive Bayes models.
What You Will Learn
- Clean text data and remove duplicates
- Explore spam vs ham with charts and word clouds
- Build a text-preprocessing function
- Vectorize text with TF-IDF
- Train and compare Naive Bayes models
- Choose the right metric (precision) for spam
Prerequisites
Stop Words, Stemming and Precision.
Project Steps
- Data cleaning
- Exploratory data analysis (EDA)
- Text preprocessing
- Model building
- Evaluation
- Improvement and deployment
Step 1: Load and Clean
import pandas as pd
data = pd.read_csv("mail_data.csv") # columns: Category, Message
print(data.shape)
data = data.rename(columns={"Category": "target", "Message": "text"})
data["target"] = (data["target"] == "spam").astype(int) # ham=0, spam=1
print(data.isnull().sum().sum(), "missing,", data.duplicated().sum(), "duplicates")
data = data.drop_duplicates(keep="first")
print(data.shape)
(5572, 2) 0 missing, 415 duplicates (5157, 2)
Explanation: The old version used LabelEncoder; mapping spam → 1 directly is clearer. Removing the 415 duplicate messages prevents the same text from appearing in both training and test sets.
Step 2: Explore
print(data["target"].value_counts())
data["target"].value_counts().plot(kind="pie", autopct="%.2f", labels=["ham", "spam"])
target 0 4516 1 641

Explanation: Only about 12% of messages are spam – the data is imbalanced, so accuracy alone will look good even for a weak model.
import nltk
data["num_characters"] = data["text"].apply(len)
data["num_words"] = data["text"].apply(lambda x: len(nltk.word_tokenize(x)))
data["num_sentences"] = data["text"].apply(lambda x: len(nltk.sent_tokenize(x)))
import seaborn as sns
sns.histplot(data[data.target == 0]["num_characters"])
sns.histplot(data[data.target == 1]["num_characters"], color="red")


Explanation: Spam messages are usually longer – they are full of offers, numbers and instructions. Length can itself be a useful feature.

Step 3: Preprocess the Text
import string
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
ps = PorterStemmer()
STOP = set(stopwords.words("english"))
def transform_text(text):
tokens = nltk.word_tokenize(text.lower())
tokens = [t for t in tokens if t.isalnum()] # drop punctuation
tokens = [t for t in tokens if t not in STOP] # drop stop words
return " ".join(ps.stem(t) for t in tokens) # stem
print(transform_text("Did you like to Travel?"))
data["transformed_text"] = data["text"].apply(transform_text)
like travel
Explanation: Lowercase → tokenize → keep only letters/digits → remove stop words → stem. The stop-word list is turned into a set once, instead of calling stopwords.words() for every word as the old code did, which makes this many times faster.
Word Clouds and Top Words
from wordcloud import WordCloud
wc = WordCloud(width=500, height=500, min_font_size=10, background_color="white")
spam_wc = wc.generate(data[data.target == 1]["transformed_text"].str.cat(sep=" "))


from collections import Counter
spam_words = " ".join(data[data.target == 1]["transformed_text"]).split()
print(Counter(spam_words).most_common(10))
[('call', 311), ('free', 186), ('2', 154), ('txt', 139), ('text', 122), ('ur', 119), ('u', 115), ('mobil', 110), ('stop', 108), ('repli', 103)]


Explanation: Spam is dominated by “call”, “free”, “txt”, “claim”, “prize”; ham by everyday words. These differences are what the model will learn.
Step 4: Vectorize with TF-IDF
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer(max_features=3000)
X = tfidf.fit_transform(data["transformed_text"]).toarray()
y = data["target"].values
print(X.shape)
(5157, 3000)
Explanation: TF-IDF gives each of the 3,000 most common words a weight per message: high if the word is frequent in this message but rare overall. The result is mostly zeros, which is why scikit-learn stores it as a sparse matrix until toarray().
Step 5: Train and Compare
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB, MultinomialNB, BernoulliNB
from sklearn.metrics import accuracy_score, confusion_matrix, precision_score
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=2)
for name, model in [("Gaussian", GaussianNB()), ("Multinomial", MultinomialNB()), ("Bernoulli", BernoulliNB())]:
y_pred = model.fit(X_train, y_train).predict(X_test)
print(name, round(accuracy_score(y_test, y_pred), 3), round(precision_score(y_test, y_pred), 3))
print(confusion_matrix(y_test, y_pred))
Gaussian 0.867 0.478 [[785 120] [ 17 110]] Multinomial 0.971 1.0 [[905 0] [ 30 97]] Bernoulli 0.984 0.982 [[903 2] [ 15 112]]
| Model | Accuracy | Precision | Comment |
|---|---|---|---|
| GaussianNB | 0.867 | 0.478 | Assumes normal features – poor fit for word weights; 120 good messages flagged |
| MultinomialNB | 0.971 | 1.000 | No good message wrongly marked as spam, but misses 30 spams |
| BernoulliNB | 0.984 | 0.982 | Best balance: catches 112 of 127 spams with only 2 false alarms |
Explanation: For a spam filter, precision matters most: putting a real message in the spam folder is worse than letting a little spam through. MultinomialNB is perfectly precise; BernoulliNB catches more spam with almost no false alarms. Both are good choices.
Bonus: Sentiment of a Message
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
print(SentimentIntensityAnalyzer().polarity_scores("Please don't text me anymore. I have nothing else to say."))
{'neg': 0.0, 'neu': 0.813, 'pos': 0.187, 'compound': 0.3182}
Explanation: VADER gives negative, neutral and positive proportions and a compound score from −1 to +1. Rule-based tools can misread negation and sarcasm – here it rates a clearly negative message as mildly positive.
Step 6: Improve and Deploy
- Add length features (characters, words) to TF-IDF.
- Try Logistic Regression, SVM or a fine-tuned transformer.
- Use a scikit-learn Pipeline and cross-validation.
- Serve it with FastAPI or a Streamlit web page.
Series
NLP series: Introduction · Tokenizer · Stop Words · Stemming · Lemmatization · WordNet · NLTK Practice · Spam Detection Project · Text to Speech · Speech Assistant · NLP Project Ideas
Interview Questions
Q: Why is precision important for spam detection?
False positives hide real messages from users, which is costly.
Q: Why MultinomialNB for text?
It models word counts/frequencies, matching how text features are distributed.
Q: What is TF-IDF?
Term frequency × inverse document frequency: highlights words that are frequent in a document but rare across documents.
Practice Exercises
- Rebuild the model inside a Pipeline and fit TF-IDF only on training data.
- Add num_characters as an extra feature and compare precision.
- Build a Streamlit app where users paste a message and see “spam” or “ham”.
Summary
We cleaned the messages, explored them, preprocessed text with NLTK, vectorized with TF-IDF and compared Naive Bayes models – MultinomialNB and BernoulliNB give high accuracy with excellent precision.
Next: Text to Speech · NLP Project Ideas
Machine Learning Tutorials, Courses and Certifications