Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 62

Spam Detection using Machine Learning

In this lesson: Build an SMS/email spam classifier with Naive Bayes in Python — text cleaning, vectorizing, accuracy — full code. In Hindi & English.

What we are building

A spam detector is a machine learning program that reads a message and decides if it is spam or not. It learns from example messages already labelled as spam or safe. This is a classic supervised classification project, built easily with the scikit-learn library.

💡 Steps: get labelled messages → turn text into numbers → train a model → predict on new messages.

How spam detection works

Spam messages tend to use certain words more often ("free", "win", "offer"). The model looks at many labelled examples, learns which words point to spam, and uses that to judge new messages. Because it learns from labelled data, it is supervised learning — specifically, classification into two classes: spam or not spam.

The data

messages = [
    "Win a free prize now",       # spam
    "Meeting at 5 pm today",      # not spam
    "Claim your free reward",     # spam
    "Lunch tomorrow?"             # not spam
]
labels = [1, 0, 1, 0]   # 1 = spam, 0 = not spam

We need messages and their labels. Here 1 means spam and 0 means not spam. Real projects use thousands of examples, but the idea is the same.

Turning text into numbers

from sklearn.feature_extraction.text import CountVectorizer

vec = CountVectorizer()
X = vec.fit_transform(messages)   # word counts as numbers

Models cannot read words, so CountVectorizer turns each message into a row of word counts. Now every message is a list of numbers the model can learn from.

Training the model

from sklearn.naive_bayes import MultinomialNB

model = MultinomialNB()
model.fit(X, labels)   # learn from the examples

MultinomialNB (Naive Bayes) is a fast, reliable model for text. fit() trains it on our numbers and labels, so it learns which words signal spam.

Making predictions

new = ["Free reward waiting for you"]
new_X = vec.transform(new)         # same vectorizer
print(model.predict(new_X))        # [1] = spam
[1]

We transform the new message with the same vectorizer, then call predict. A result of 1 means the model thinks it is spam. That is a working spam detector.

Common mistakes

  • Using a different vectorizer for new data. Use transform with the same fitted vectorizer, not a new one.
  • Too little data. A few examples cannot learn well — real models use many messages.
  • Not splitting train and test. Check accuracy on unseen data to avoid fooling yourself.
  • Forgetting to clean text. Lowercasing and removing punctuation usually improves results.

Summary

  • Spam detection is supervised classification: spam or not spam.
  • Turn text into numbers with CountVectorizer (or TF-IDF).
  • Train a MultinomialNB model with fit().
  • Predict new messages with the same vectorizer and predict().
  • Use plenty of data and a train/test split for a reliable model.

Next, understand the ML type in supervised learning, or check model quality with overfitting and underfitting.

Frequently Asked Questions

How does machine learning detect spam?
It learns from many example messages already labelled "spam" or "not spam". It notices which words appear more in spam, then uses that pattern to judge new messages. It is a supervised classification problem.
Why do we turn text into numbers?
Machine learning models work with numbers, not raw words. We convert each message into a count of its words (a vector) using CountVectorizer or TF-IDF, so the model can do maths on it.
What algorithm is good for spam detection?
Naive Bayes (MultinomialNB) is a classic, fast choice for text classification like spam. It works well with word counts and trains quickly, which is why it is a popular first model for this task.
What library do I use in Python?
scikit-learn (sklearn) provides the vectorizer, the model, and the train/test tools all together. Install it with pip install scikit-learn.
How do I know if the spam model is good?
Split your data into training and test sets, train on one and check accuracy on the other. Good accuracy on unseen test data means the model generalises rather than just memorising.
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicTic-Tac-Toe Game Your progress: 62 / 66 (94%) · Lesson 63 / 66 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free