🧠 AI Computer Institute
Content is AI-generated for educational purposes. Verify critical information independently. A bharath.ai initiative.

Your First ML Classifier: Building a Spam Filter

📚 Introduction to Machine Learning⏱️ 19 min read🎓 Grade 9

Your First ML Classifier: Building a Spam Filter

What is Spam and Why Filter It?

Spam: Unsolicited messages, often trying to trick users into clicking links or sharing personal info.

Types of Spam:

  • Email spam: Phishing, promotional emails, scams
  • SMS spam: OTP scams, loan offers, prize claims targeting Indian phone users
  • Social media spam: Fake profiles, spam comments
  • Web spam: Spammy comments, malicious links

Text Classification Pipeline

  1. Collect spam and non-spam messages
  2. Preprocess text (lowercase, remove punctuation, etc.)
  3. Convert text to numerical features
  4. Train classifier
  5. Evaluate performance
  6. Deploy and monitor

Step 1: Text Preprocessing


import re
import string

def preprocess_text(text): """Clean and preprocess text""" # Lowercase text = text.lower() # Remove URLs text = re.sub(r'httpS+|wwwS+', '', text) # Remove email addresses text = re.sub(r'S+@S+', '', text) # Remove punctuation text = text.translate(str.maketrans('', '', string.punctuation)) # Remove extra whitespace text = ' '.join(text.split()) return text

# Example
spam_msg = "CLICK NOW!!! Win Prize at www.scam.com Or call 9999999999!!!"
print(preprocess_text(spam_msg))
# output: click now win prize or call 9999999999

Step 2: Feature Extraction - Bag of Words

Bag of Words: Represent text as collection of word occurrences, ignoring order.


from sklearn.feature_extraction.text import CountVectorizer

# Sample messages
messages = [ "Click here to win free prize", "Meeting at 2pm tomorrow", "Urgent action required confirm account", "Can you call me back",
]

# Create bag of words
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(messages)

# Show feature names (unique words)
print(vectorizer.get_feature_names_out())
# ['account', 'action', 'back', 'call', 'can', 'click', ...]

# Show sparse matrix (words count in each message)
print(X.toarray())
# [[0 0 0 0 0 1 0 1 ...],  # message 1
#  [0 0 0 0 0 0 0 0 ...],  # message 2
#  ...]

Step 3: Feature Extraction - TF-IDF

TF-IDF: Term Frequency-Inverse Document Frequency. Weight words: common words get lower weight, rare words get higher weight.

Why TF-IDF is better than Bag of Words:

  • Common words like "the", "is", "a" get low weight (not useful for classification)
  • Spam-specific words like "win", "prize", "click" get high weight
  • Better discrimination between spam and ham

from sklearn.feature_extraction.text import TfidfVectorizer

# Create TF-IDF features
tfidf = TfidfVectorizer(max_features=100)  # top 100 words
X_tfidf = tfidf.fit_transform(messages)

print(X_tfidf.toarray())
# Values between 0 and 1, representing importance of each word

Step 4: Training - Naive Bayes Classifier

Naive Bayes: Probabilistic classifier based on Bayes theorem. "Naive" assumes features are independent.

How it works:


# P(Spam | Message) = P(Message | Spam) * P(Spam) / P(Message)
# 
# P(Spam | Message): Probability message is spam given words in it
# P(Message | Spam): Probability of words given message is spam
# P(Spam): Prior probability of spam (% of training data that is spam)
# P(Message): Probability of message (normalization constant)

# Simple example:
# Word "free" appears in 80% of spam, 5% of ham
# Word "meeting" appears in 2% of spam, 40% of ham
# Message contains "free": likely spam
# Message contains "meeting": likely ham

Complete Spam Filter Implementation


from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix

# Sample dataset
messages = [ # Spam messages "Click here to win free money", "Congratulations you won a prize", "Urgent action required verify account", "Limited time offer claim now", # Ham (legitimate) messages "Hi how are you doing", "Meeting scheduled for tomorrow", "Can we discuss the project", "Thanks for your message",
]

labels = [1, 1, 1, 1, 0, 0, 0, 0]  # 1: spam, 0: ham

# Split data
X_train, X_test, y_train, y_test = train_test_split( messages, labels, test_size=0.25, random_state=42
)

# Create pipeline: TF-IDF + Naive Bayes
pipeline = Pipeline([ ('tfidf', TfidfVectorizer(max_features=50)), ('classifier', MultinomialNB())
])

# Train
pipeline.fit(X_train, y_train)

# Predict
y_pred = pipeline.predict(X_test)

# Evaluate
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2%}")

Step 5: Evaluation - Confusion Matrix

Confusion Matrix: Shows correct and incorrect predictions.


from sklearn.metrics import confusion_matrix, classification_report
import numpy as np

# Predictions vs actual
y_actual = [1, 0, 1, 0, 1, 0]
y_predicted = [1, 0, 0, 0, 1, 1]

# Confusion matrix
cm = confusion_matrix(y_actual, y_predicted)
print(cm)
# [[3 1]  -> True Negatives (TN=3), False Positives (FP=1)
#  [1 1]] -> False Negatives (FN=1), True Positives (TP=1)

# Detailed metrics
print(classification_report(y_actual, y_predicted))

Metrics Explained

MetricFormulaMeaningIn Spam Filter
True Positive (TP)-Spam predicted as spamCorrectly blocked spam
True Negative (TN)-Ham predicted as hamLegitimate message delivered
False Positive (FP)-Ham predicted as spamGood email goes to spam (bad!)
False Negative (FN)-Spam predicted as hamSpam reaches inbox (bad!)
Accuracy(TP+TN)/(TP+TN+FP+FN)% correctNot always best metric
PrecisionTP/(TP+FP)Of predicted spam, % correctMinimize false positives
RecallTP/(TP+FN)Of actual spam, % caughtCatch most spam

India Context: SMS Spam Problem

Indian phone users receive ~400 million spam SMS daily. Common patterns:

Common Spam Patterns in India

  • Loan offers: "Loan upto 5 lakhs at 2% interest. Approve in 5 mins"
  • OTP scams: "Your OTP is 123456. Don't share with anyone"
  • Prize claims: "Congratulations! You won 1 lakh rupees. Claim now"
  • Job offers: "Work from home, earn 50k/month. No investment needed"
  • Crypto scams: "Bitcoin trading app - guaranteed 100% returns"

Build a Simple Hindi Spam Detector


# Hindi spam messages
hindi_messages = [ "क्लिक करें और जीतें 10 लाख रुपये",  # Click and win 10 lakh rupees "आपका OTP है 123456", # Your OTP is 123456 "घर बैठे 50,000 कमाएं", # Earn 50,000 sitting at home "कल मीटिंग है 2 बजे", # Meeting tomorrow at 2pm "धन्यवाद आपके संदेश के लिए", # Thanks for your message
]

labels = [1, 1, 1, 0, 0]  # spam, spam, spam, ham, ham

# TF-IDF will work with Hindi text (UTF-8 encoded)
tfidf = TfidfVectorizer()
X = tfidf.fit_transform(hindi_messages)

classifier = MultinomialNB()
classifier.fit(X, labels)

# Test on new message
new_msg = ["लाभ उठाएं खास ऑफर पर"]  # Take advantage of special offer
prediction = classifier.predict(tfidf.transform(new_msg))
print(f"Prediction: {'Spam' if prediction[0] else 'Ham'}")  # Spam

Advanced: Why Naive Bayes Works for Spam

  • Fast: O(n) training, O(1) prediction
  • Scalable: Can handle millions of messages
  • Works with text: Naturally suited for word frequencies
  • Probabilistic: Can output confidence scores
  • Few parameters: Easy to tune

Why "Naive"?

Assumes all words are independent. In reality, they're not:

  • "Free" and "money" often appear together
  • "Meeting" and "tomorrow" often appear together

But despite this, Naive Bayes works surprisingly well in practice for text!

Improving Your Spam Filter

  1. More data: Train on thousands of real spam/ham messages
  2. Feature engineering: Add features like sender domain, message length, caps count
  3. Ensemble methods: Combine multiple classifiers (voting)
  4. Deep learning: Use neural networks for complex patterns
  5. Online learning: Update model as new spam patterns emerge
  6. Multilingual: Handle Hindi, Tamil, Telugu, etc.

Practice Problems

  1. Build a spam filter using the provided code on your own dataset.
  2. Compare Bag of Words vs TF-IDF features on spam classification.
  3. Implement Naive Bayes from scratch (calculate probabilities manually).
  4. Create confusion matrix and compute precision/recall for spam filter.
  5. Build a Hindi SMS spam detector for Indian phone numbers.
  6. Experiment with different hyperparameters (max_features, ngrams).

Complete Working Example


from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, precision_score, recall_score

# Real spam/ham dataset (simplified)
spam_messages = [ "Click now to win free money", "Congratulations you are selected", "Verify your account urgently", "Limited offer act now", "Claim free prize today",
]

ham_messages = [ "Can you call me back", "Meeting scheduled at 2pm", "Thanks for the update", "Let's discuss the project", "How are you doing today",
]

all_messages = spam_messages + ham_messages
labels = [1]*len(spam_messages) + [0]*len(ham_messages)

# Vectorize
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(all_messages)

# Train classifier
classifier = MultinomialNB()
classifier.fit(X, labels)

# Test on new messages
test_messages = [ "Verify account now to win prize", "Can we meet tomorrow", "Claim free money instantly",
]

predictions = classifier.predict(vectorizer.transform(test_messages))
probabilities = classifier.predict_proba(vectorizer.transform(test_messages))

for msg, pred, prob in zip(test_messages, predictions, probabilities): print(f"Message: {msg}") print(f"Prediction: {'SPAM' if pred else 'HAM'}") print(f"Confidence: {max(prob):.2%}
")

Key Takeaways

  • Spam filtering is a text classification problem with two classes: spam and ham.
  • Preprocessing: lowercase, remove URLs, remove punctuation, clean whitespace.
  • Bag of Words: count word frequencies (simple but ignores importance).
  • TF-IDF: weight by importance (better - rare spam words get high weight).
  • Naive Bayes: probabilistic classifier, fast, scalable, works great for text.
  • Evaluation: Accuracy, Precision, Recall, F1-score, Confusion Matrix.
  • In spam filters, precision is crucial (don't want legitimate emails in spam).
  • India: Major problem with SMS spam (loan offers, OTP scams, job scams).
  • Production: Continuous monitoring and retraining as spam patterns evolve.

Under the Hood: Your First ML Classifier: Building a Spam Filter

Here is what separates someone who merely USES technology from someone who UNDERSTANDS it: knowing what happens behind the screen. When you tap "Send" on a WhatsApp message, do you know what journey that message takes? When you search something on Google, do you know how it finds the answer among billions of web pages in less than a second? When UPI processes a payment, what makes sure the money goes to the right person?

Understanding Your First ML Classifier: Building a Spam Filter gives you the ability to answer these questions. More importantly, it gives you the foundation to BUILD things, not just use things other people built. India's tech industry employs over 5 million people, and companies like Infosys, TCS, Wipro, and thousands of startups are all built on the concepts we are about to explore.

This is not just theory for exams. This is how the real world works. Let us get into it.

Neural Networks: Layers of Learning

A neural network is inspired by how your brain works. Your brain has billions of neurons connected to each other. When you see, hear, or think something, electrical signals flow through these connections. A neural network simulates this with layers of mathematical operations:

  INPUT LAYER HIDDEN LAYERS OUTPUT LAYER (Raw Data) (Feature Extraction) (Decision) Pixel 1 ──┐ Pixel 2 ──┤ ┌─[Neuron]─┐ Pixel 3 ──┼───▶│ Edges & │───┐ Pixel 4 ──┤ │ Corners │ │ ┌─[Neuron]─┐ Pixel 5 ──┤ └───────────┘ ├───▶│ Face │──▶ "It's a cat!" (92%) ... │ ┌─[Neuron]─┐ │ │ Features │ "It's a dog" (7%) Pixel N ──┤ │ Shapes & │───┘ │ + Body │ "Other" (1%) └───▶│ Textures │───────▶│ Shape │ └───────────┘ └──────────┘ Layer 1: Detects simple features (edges, gradients) Layer 2: Combines into complex features (eyes, ears, whiskers) Layer 3: Makes the final decision based on all features

Each connection between neurons has a "weight" — a number that determines how important that connection is. During training, the network adjusts these weights to minimise errors. This is done using an algorithm called backpropagation combined with gradient descent. The loss function measures how wrong the network is, and gradient descent follows the slope downhill to find better weights.

Modern networks like GPT-4 have billions of parameters (weights) and are trained on massive GPU clusters. India's Sarvam AI is training models specifically for Indian languages — Hindi, Tamil, Telugu, Bengali, and more — because global models often perform poorly on Indic scripts and cultural contexts.

Did You Know?

🚀 ISRO is the world's 4th largest space agency, powered by Indian engineers. With a budget smaller than some Hollywood blockbusters, ISRO does things that cost 10x more for other countries. The Mangalyaan (Mars Orbiter Mission) proved India could reach Mars for the cost of a film. Chandrayaan-3 succeeded where others failed. This is efficiency and engineering brilliance that the world studies.

🏥 AI-powered healthcare diagnosis is being developed in India. Indian startups and research labs are building AI systems that can detect cancer, tuberculosis, and retinopathy from images — better than human doctors in some cases. These systems are being deployed in rural clinics across India, bringing world-class healthcare to millions who otherwise could not afford it.

🌾 Agriculture technology is transforming Indian farming. Drones with computer vision scan crop health. IoT sensors in soil measure moisture and nutrients. AI models predict yields and optimal planting times. Companies like Ninjacart and SoilCompanion are using these technologies to help farmers earn 2-3x more. This is computer science changing millions of lives in real-time.

💰 India has more coding experts per capita than most Western countries. India hosts platforms like CodeChef, which has over 15 million users worldwide. Indians dominate competitive programming rankings. Companies like Flipkart and Razorpay are building world-class engineering cultures. The talent is real, and if you stick with computer science, you will be part of this story.

Real-World System Design: Swiggy's Architecture

When you order food on Swiggy, here is what happens behind the scenes in about 2 seconds: your location is geocoded (algorithms), nearby restaurants are queried from a spatial index (data structures), menu prices are pulled from a database (SQL), delivery time is estimated using ML models trained on historical data (AI), the order is placed in a distributed message queue (Kafka), a delivery partner is assigned using a matching algorithm (optimization), and real-time tracking begins using WebSocket connections (networking). EVERY concept in your CS curriculum is being used simultaneously to deliver your biryani.

The Process: How Your First ML Classifier: Building a Spam Filter Works in Production

In professional engineering, implementing your first ml classifier: building a spam filter requires a systematic approach that balances correctness, performance, and maintainability:

Step 1: Requirements Analysis and Design Trade-offs
Start with a clear specification: what does this system need to do? What are the performance requirements (latency, throughput)? What about reliability (how often can it fail)? What constraints exist (memory, disk, network)? Engineers create detailed design documents, often including complexity analysis (how does the system scale as data grows?).

Step 2: Architecture and System Design
Design the system architecture: what components exist? How do they communicate? Where are the critical paths? Use design patterns (proven solutions to common problems) to avoid reinventing the wheel. For distributed systems, consider: how do we handle failures? How do we ensure consistency across multiple servers? These questions determine the entire architecture.

Step 3: Implementation with Code Review and Testing
Write the code following the architecture. But here is the thing — it is not a solo activity. Other engineers read and critique the code (code review). They ask: is this maintainable? Are there subtle bugs? Can we optimize this? Meanwhile, automated tests verify every piece of functionality, from unit tests (testing individual functions) to integration tests (testing how components work together).

Step 4: Performance Optimization and Profiling
Measure where the system is slow. Use profilers (tools that measure where time is spent). Optimize the bottlenecks. Sometimes this means algorithmic improvements (choosing a smarter algorithm). Sometimes it means system-level improvements (using caching, adding more servers, optimizing database queries). Always profile before and after to prove the optimization worked.

Step 5: Deployment, Monitoring, and Iteration
Deploy gradually, not all at once. Run A/B tests (comparing two versions) to ensure the new system is better. Once live, monitor relentlessly: metrics dashboards, logs, traces. If issues arise, implement circuit breakers and graceful degradation (keeping the system partially functional rather than crashing completely). Then iterate — version 2.0 will be better than 1.0 based on lessons learned.


Algorithm Complexity and Big-O Notation

Big-O notation describes how an algorithm's performance scales with input size. This is THE most important concept for coding interviews:

  BIG-O COMPARISON (n = 1,000,000 elements): O(1) Constant 1 operation Hash table lookup O(log n) Logarithmic  20 operations Binary search O(n) Linear 1,000,000 ops Linear search O(n log n)  Linearithmic 20,000,000 ops Merge sort, Quick sort O(n²) Quadratic 1,000,000,000,000 Bubble sort, Selection sort O(2ⁿ) Exponential  ∞ (universe dies) Brute force subset Time at 1 billion ops/sec: O(n log n): 0.02 seconds ← Perfectly usable O(n²): 11.5 DAYS ← Completely unusable! O(2ⁿ): Longer than the age of the universe # Python example: Merge Sort (O(n log n)) def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) # Sort left half right = merge_sort(arr[mid:]) # Sort right half return merge(left, right) # Merge sorted halves def merge(left, right): result = [] i = j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]); i += 1 else: result.append(right[j]); j += 1 result.extend(left[i:]) result.extend(right[j:]) return result

This matters in the real world. India's Aadhaar system must search through 1.4 billion biometric records for every authentication request. At O(n), that would take seconds per request. With the right data structures (hash tables, B-trees), it takes milliseconds. The algorithm choice is the difference between a working system and an unusable one.

Real Story from India

The India Stack Revolution

In the early 1990s, India's economy was closed. Indians could not easily send money abroad or access international services. But starting in 1991, India opened its economy. Young engineers in Bangalore, Hyderabad, and Chennai saw this as an opportunity. They built software companies (Infosys, TCS, Wipro) that served the world.

Fast forward to 2008. India had a problem: 500 million Indians had no formal identity. No bank account, no passport, no way to access government services. The government decided: let us use technology to solve this. UIDAI (Unique Identification Authority of India) was created, and engineers designed Aadhaar.

Aadhaar collects fingerprints and iris scans from every Indian, stores them in massive databases using sophisticated encryption, and allows anyone (even a street vendor) to verify identity instantly. Today, 1.4 billion Indians have Aadhaar. On top of Aadhaar, engineers built UPI (digital payments), Jan Dhan (bank accounts), and ONDC (open e-commerce network).

This entire stack — Aadhaar, UPI, Jan Dhan, ONDC — is called the India Stack. It is considered the most advanced digital infrastructure in the world. Governments and companies everywhere are trying to copy it. And it was built by Indian engineers using computer science concepts that you are learning right now.

Production Engineering: Your First ML Classifier: Building a Spam Filter at Scale

Understanding your first ml classifier: building a spam filter at an academic level is necessary but not sufficient. Let us examine how these concepts manifest in production environments where failure has real consequences.

Consider India's UPI system processing 10+ billion transactions monthly. The architecture must guarantee: atomicity (a transfer either completes fully or not at all — no half-transfers), consistency (balances always add up correctly across all banks), isolation (concurrent transactions on the same account do not interfere), and durability (once confirmed, a transaction survives any failure). These are the ACID properties, and violating any one of them in a payment system would cause financial chaos for millions of people.

At scale, you also face the thundering herd problem: what happens when a million users check their exam results at the same time? (CBSE result day, anyone?) Without rate limiting, connection pooling, caching, and graceful degradation, the system crashes. Good engineering means designing for the worst case while optimising for the common case. Companies like NPCI (the organisation behind UPI) invest heavily in load testing — simulating peak traffic to identify bottlenecks before they affect real users.

Monitoring and observability become critical at scale. You need metrics (how many requests per second? what is the 99th percentile latency?), logs (what happened when something went wrong?), and traces (how did a single request flow through 15 different microservices?). Tools like Prometheus, Grafana, ELK Stack, and Jaeger are standard in Indian tech companies. When Hotstar streams IPL to 50 million concurrent users, their engineering team watches these dashboards in real-time, ready to intervene if any metric goes anomalous.

The career implications are clear: engineers who understand both the theory (from chapters like this one) AND the practice (from building real systems) command the highest salaries and most interesting roles. India's top engineering talent earns ₹50-100+ LPA at companies like Google, Microsoft, and Goldman Sachs, or builds their own startups. The foundation starts here.

Checkpoint: Test Your Understanding 🎯

Before moving forward, ensure you can answer these:

Question 1: Explain the tradeoffs in your first ml classifier: building a spam filter. What is better: speed or reliability? Can we have both? Why or why not?

Answer: Good engineers understand that there are always tradeoffs. Optimal depends on requirements — is this a real-time system or batch processing?

Question 2: How would you test if your implementation of your first ml classifier: building a spam filter is correct and performant? What would you measure?

Answer: Correctness testing, performance benchmarking, edge case handling, failure scenarios — just like professional engineers do.

Question 3: If your first ml classifier: building a spam filter fails in a production system (like UPI), what happens? How would you design to prevent or recover from failures?

Answer: Redundancy, failover systems, circuit breakers, graceful degradation — these are real concerns at scale.

Key Vocabulary

Here are important terms from this chapter that you should know:

Neural Network: An important concept in Introduction to Machine Learning
Gradient: An important concept in Introduction to Machine Learning
Epoch: An important concept in Introduction to Machine Learning
Loss Function: An important concept in Introduction to Machine Learning
Backpropagation: An important concept in Introduction to Machine Learning

💡 Interview-Style Problem

Here is a problem that frequently appears in technical interviews at companies like Google, Amazon, and Flipkart: "Design a URL shortener like bit.ly. How would you generate unique short codes? How would you handle millions of redirects per second? What database would you use and why? How would you track click analytics?"

Think about: hash functions for generating short codes, read-heavy workload (99% redirects, 1% creates) suggesting caching, database choice (Redis for cache, PostgreSQL for persistence), and horizontal scaling with consistent hashing. Try sketching the system architecture on paper before looking up solutions. The ability to think through system design problems is the single most valuable skill for senior engineering roles.

Where This Takes You

The knowledge you have gained about your first ml classifier: building a spam filter is directly applicable to: competitive programming (Codeforces, CodeChef — India has the 2nd largest competitive programming community globally), open-source contribution (India is the 2nd largest contributor on GitHub), placement preparation (these concepts form 60% of technical interview questions), and building real products (every startup needs engineers who understand these fundamentals).

India's tech ecosystem offers incredible opportunities. Freshers at top companies earn ₹15-50 LPA; experienced engineers at FAANG companies in India earn ₹50-1 Cr+. But more importantly, the problems being solved in India — digital payments for 1.4 billion people, healthcare AI for rural areas, agricultural tech for 150 million farmers — are some of the most impactful engineering challenges in the world. The fundamentals you are building will be the tools you use to tackle them.

Crafted for Class 7–9 • Introduction to Machine Learning • Aligned with NEP 2020 & CBSE Curriculum

← Data Collection and Cleaning: Garbage In, Garbage OutLinear Regression by Hand: Understanding the Math →

Found this useful? Share it!

📱 WhatsApp 🐦 Twitter 💼 LinkedIn