+91 99301 12627
Machine Learning

Naive Bayes Explained: How It Works, Types and a Python Spam Filter Example

By Mehul Prajapati

Smartphone mail app icon representing Naive Bayes spam filtering
On this page

Naive Bayes is a fast, simple classification algorithm based on Bayes’ theorem. It calculates the probability that an item belongs to each class (for example spam or not spam) from the features it contains, and picks the most likely class. It is called naive because it assumes every feature is independent of the others given the class. That assumption is rarely true, yet Naive Bayes still works surprisingly well, especially for text classification such as spam filtering, sentiment analysis and news categorisation.

Bayes’ theorem in one line

P(class | features) = P(features | class) × P(class) / P(features)

  • P(class) is the prior: how common the class is before you look at the data.
  • P(features | class) is the likelihood: how often these features appear in that class.
  • P(class | features) is the posterior: the updated probability after seeing the features. This is what we want.

A worked example: is this message spam?

Suppose that in your inbox history:

  • 40% of messages are spam, so P(spam) = 0.4 and P(not spam) = 0.6.
  • The word “free” appears in 60% of spam messages and in 5% of normal messages.

A new message contains “free”. What is the probability it is spam?

  • Spam side: 0.6 × 0.4 = 0.24
  • Not-spam side: 0.05 × 0.6 = 0.03
  • P(spam | “free”) = 0.24 / (0.24 + 0.03) ≈ 0.89

So the message is about 89% likely to be spam. With many words, Naive Bayes simply multiplies the likelihood of each word (that is the independence assumption) and compares the totals for each class.

Why is it called “naive”?

In real text, words are not independent: “claim” and “prize” often appear together. Naive Bayes ignores those relationships and treats each word as separate evidence. This makes the maths very cheap and needs little training data. The probability values it produces can be over-confident, but the ranking of classes is often correct, which is all a classifier needs.

Types of Naive Bayes

Type Feature type Typical use scikit-learn class
Gaussian Continuous numbers, assumed normally distributed Sensor readings, measurements, the Iris dataset GaussianNB
Multinomial Counts, such as word counts or TF-IDF Spam filters, topic classification MultinomialNB
Bernoulli Binary yes/no features (word present or absent) Short texts, binary feature sets BernoulliNB
Complement Counts, with imbalanced classes Text data where one class dominates ComplementNB

Laplace smoothing: the zero-probability problem

If a word never appeared in spam during training, its likelihood for spam is 0, and multiplying by 0 wipes out all other evidence. Laplace (additive) smoothing adds a small count, usually 1, to every word so no probability is exactly zero. In scikit-learn this is the alpha parameter, and it is worth tuning.

Build a spam filter in Python

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline

messages = [
    "Win a free iPhone now, click the link",
    "Congratulations, you won a cash prize, claim now",
    "Limited offer: free recharge, click here",
    "Are we meeting for the Python class tomorrow?",
    "Please share the SQL notes from today",
    "Can you call me after the project review?",
]
labels = ["spam", "spam", "spam", "ham", "ham", "ham"]

model = make_pipeline(CountVectorizer(), MultinomialNB(alpha=1.0))
model.fit(messages, labels)

tests = ["Click now to claim your free prize", "Share the Python notes after class"]
print(model.predict(tests))
print(model.predict_proba(tests).round(3), model.classes_)

When we ran this (scikit-learn 1.9), it printed ['spam' 'ham']. The first message got a spam probability of about 0.993 and the second a ham probability of about 0.979. Six training messages is only a demonstration; a real filter needs thousands of labelled examples, a train/test split and proper evaluation, as explained in how to evaluate a machine learning model.

Advantages and limitations

Advantages Limitations
Very fast to train and predict, even on large text datasets The independence assumption ignores word combinations and context
Works well with small training sets Probability scores are often over-confident
Handles many features (thousands of words) easily Gaussian NB struggles when numeric features are far from normally distributed
Easy to explain and a strong baseline Usually beaten by logistic regression, gradient boosting or transformers when data is plentiful

When should you use Naive Bayes?

  • As a quick baseline for any text classification task, before trying heavier models.
  • When you need very fast predictions or have limited computing power.
  • When you have little labelled data.
  • For spam detection, support-ticket routing, sentiment and simple document categorisation.

For tabular business data with interacting features, try logistic regression or decision trees and random forests as well, and compare them on the same validation set.

Frequently asked questions

Is Naive Bayes supervised or unsupervised?

Supervised. It learns from labelled examples, such as messages already marked spam or not spam.

Why does Naive Bayes work well for text?

Text produces thousands of word features, and Naive Bayes handles high-dimensional, sparse data efficiently. Even though words are not truly independent, the combined evidence from many words usually points to the right class.

What is the difference between Naive Bayes and logistic regression?

Naive Bayes is a generative model: it models how features are produced for each class and applies Bayes’ theorem. Logistic regression is discriminative: it learns the decision boundary directly. Naive Bayes often wins with very little data; logistic regression usually wins as data grows.

Do I need to scale features for Naive Bayes?

Not for Multinomial or Bernoulli NB on counts. Gaussian NB models each feature’s own mean and variance, so scaling is not required, but transforming heavily skewed features can help.

Want to build classifiers like this on real datasets with guidance? See our Machine Learning course or the complete Data Science course.

A note from Mehul Prajapati

I have spent 18+ years in IT and training and have personally mentored 12,000+ students. If you are planning your next step in machine learning and want a second opinion on your learning path, I am happy to help.

“The technology you learn today may change tomorrow, but your ability to learn will always be your biggest strength. Stay curious, keep upgrading yourself, and never stop growing.”

Message me on WhatsApp at +91 99301 12627 and tell me which blog you read. I would love to hear from you.

Learn with Mehul Prajapati in Borivali West

At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support and placement assistance on the Machine Learning course. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.

Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072

Visit the centre or call us to choose the right course and batch and to know the current fee structure.