Bayesian Thinking

There are two camps in statistics: Bayesians and frequentists. They are fundamentally different ways of thinking about probability and uncertainty.[1]

The Bayesians treat probability as a measure of belief rather than just frequencies of events. It all sounds very reasonable, but in practice, it’s pretty tricky.

In this lesson, we’ll just scratch the surface.

This Lesson Will Cover
  • 🔍 Bayesian vs. Frequentist Statistics and their fundamental differences
  • 📏 Bayes’ Theorem and its role in updating probabilities
  • 📩 Naive Bayes Classifier and its application in spam detection
  • 🚀 Bayesian Optimization in machine learning
  • 🌍 Real-world applications of Bayesian statistics
Bayesian Thinking in a Nutshell
Bayesian thinking in a nutshell.

Bayesian vs Frequentist Statistics

Fundamental Differences

Aspect Bayesian Frequentist
Definition of Probability Probability represents a degree of belief that can be updated with new evidence Probability represents the long-run frequency of events in repeated experiments
Parameters Parameters are treated as random variables with probability distributions Parameters are fixed, unknown constants
Prior Knowledge Explicitly incorporates prior knowledge through prior distributions Typically doesn’t use prior knowledge, focuses only on data
Results Interpretation “There’s a 95% probability that the parameter lies in this interval” “If we repeated this experiment many times, 95% of intervals would contain the true parameter”

The Basics of Bayesian Thinking

Bayesian thinking revolves around Bayes’ Theorem, which describes how to update probabilities based on new evidence. It’s expressed as:

P(A∣B)=P(B∣A)⋅P(A)P(B) P(A | B) = \frac{P(B | A) \cdot P(A)}{P(B)}

Here we have:

Term Symbol Description
Prior Probability P(A)P(A) Your belief about AA before seeing any data
Likelihood P(B∣A)P(B | A) The probability of observing BB given that AA is true
Marginal Probability P(B)P(B) The total probability of BB across all possible scenarios
Posterior Probability P(A∣B)P(A | B) Your updated belief about AA after observing BB

Updating Beliefs

Bayesian thinking emphasizes iterative updates as new evidence arrives.

Bayesian Probability Update Flow
Priors absorb new evidence to become more realistic (and actionable) posteriors in Bayesian thinking.

Consider spam detection:

  • Prior belief: 10% chance any email is spam → P(Spam)=0.1P(\text{Spam}) = 0.1
  • Evidence: The email contains “Buy now!”, which occurs in 90% of spam emails but only 1% of non-spam emails.

Using Bayes’ Theorem, we calculate the posterior:

P(Spam | Buy now!)=P(Buy now! | Spam)⋅P(Spam)P(Buy now!) P(\text{Spam | Buy now!}) = \frac{P(\text{Buy now! | Spam}) \cdot P(\text{Spam})}{P(\text{Buy now!})}

Where:

  • P(Buy now! | Spam)=0.90P(\text{Buy now! | Spam}) = 0.90
  • P(Spam)=0.10P(\text{Spam}) = 0.10
  • P(Buy now!)=(0.90×0.10)+(0.01×0.90)=0.099P(\text{Buy now!}) = (0.90 \times 0.10) + (0.01 \times 0.90) = 0.099

Therefore:

P(Spam | Buy now!)=0.090.099≈0.91 P(\text{Spam | Buy now!}) = \frac{0.09}{0.099} \approx 0.91

So after seeing “Buy now!” in the email, our belief that it’s spam increases to 91% (compared to the prior belief of 10%).

Example: Naive Bayes Classifier

The Naive Bayes Classifier applies this type of Bayesian thinking under the assumption of feature independence. It calculates:

P(C∣X)∝P(X∣C)⋅P(C) P(C | X) \propto P(X | C) \cdot P(C)

Where:

  • CC is the class label (e.g., Spam/Not Spam).
  • XX is the observed data.
Naive Bayes Spam Detection Flowchart - End-to-End Naive Bayes Email Classifier
A visual guide to the Naive Bayes Classification example below for labeling emails as Spam or Not Spam, based on the email text.

Since we haven’t been able to look at much code in this section, here’s a Python implementation:

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

# Data
emails = ["Buy now!", "Limited offer", "Hello friend", "Meeting schedule"]
labels = [1, 1, 0, 0]  # 1 = Spam, 0 = Not Spam

# Transform text to feature vectors
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(emails)

# Train Naive Bayes model
model = MultinomialNB()
model.fit(X, labels)

# Predict on new data
test_email = vectorizer.transform(["Special offer"])
prediction = model.predict(test_email)
prediction_proba = model.predict_proba(test_email)


if prediction[0] == 0:
    print(f"Not Spam ({prediction_proba[0][0]:.2f}% probability)")
elif prediction[0] == 1:
    print(f"Spam ({prediction_proba[0][1]:.2f}% probability)")

# Output:
# Spam (0.67% probability)

To give a flavor of how this works, let’s walk through some of the algorithm:

  1. Vectorization: The CountVectorizer creates a vocabulary and transforms our emails into word frequency vectors:

    Vocabulary = {"buy", "now", "limited", "offer", "hello", "friend", "meeting", "schedule"}
    

    Then we can embed the emails as vectors in this space, i.e.

    Email buy now limited offer hello friend meeting schedule
    “Buy now!” 1 1 0 0 0 0 0 0
    “Limited offer” 0 0 1 1 0 0 0 0
    “Hello friend” 0 0 0 0 1 1 0 0
    “Meeting schedule” 0 0 0 0 0 0 1 1
  2. Prior Probabilities: The classifier calculates P(C)P(C) for each class. Since we have 2 spam emails and 2 non-spam emails in our dataset, we assign them a 50/50 chance:

    P(Spam)=24=0.5 P(\text{Spam}) = \frac{2}{4} = 0.5
    P(Not Spam)=24=0.5 P(\text{Not Spam}) = \frac{2}{4} = 0.5
  3. Likelihood Calculation: For each word ww in vocabulary, calculate P(w∣C)P(w|C) using Laplace smoothing with α=1\alpha = 1:

    P(w∣Class)=word_count_in_class+αtotal_words_in_class+α×vocabulary_size P(w|\text{Class}) = \frac{\text{word\_count\_in\_class} + \alpha}{\text{total\_words\_in\_class} + \alpha \times \text{vocabulary\_size}}

    For example:

    P("buy"∣Spam)=1+14+8=0.167 P(\text{"buy"}|\text{Spam}) = \frac{1 + 1}{4 + 8} = 0.167
    P("buy"∣Not Spam)=0+14+8=0.083 P(\text{"buy"}|\text{Not Spam}) = \frac{0 + 1}{4 + 8} = 0.083
  4. Classification
    For a new email “Special offer”, the classifier computes:

    P(Spam∣"Special offer")∝P("Special"∣Spam)×P("offer"∣Spam)×P(Spam) P(\text{Spam}|\text{"Special offer"}) \propto P(\text{"Special"}|\text{Spam}) \times P(\text{"offer"}|\text{Spam}) \times P(\text{Spam})
    P(Not Spam∣"Special offer")∝P("Special"∣Not Spam)×P("offer"∣Not Spam)×P(Not Spam) P(\text{Not Spam}|\text{"Special offer"}) \propto P(\text{"Special"}|\text{Not Spam}) \times P(\text{"offer"}|\text{Not Spam}) \times P(\text{Not Spam})

    The class with the higher probability is chosen as the prediction.

Applications in Machine Learning

Here are a few places we might run into Bayesian statistics with ML/AI and data science:

  • Probabilistic Models

    • Naive Bayes Classifier (like we saw above), Bayesian Neural Networks, Hidden Markov Models, Latent Dirichlet Allocation.
  • Bayesian Optimization

    • Hyperparameter tuning for machine learning models, A/B testing and experimental design.
  • Real-World Decision Making

    • Guide decisions in applications like medical diagnosis, recommendation systems, fraud detection.

Conclusion

I tried to be in the Bayesian camp. I tried really hard. I read a book about it, I learned how to use PyMC (a Python library for Bayesian modeling) and even shipped a project with it.[1:1]

Yet somehow it seems that I always drift back to my frequentist ways. But who knows, maybe if I keep trying then I’ll become a true Bayesian some day!

Key Takeaways

🎲 Bayesians and frequentists approach probability differently.

🔢 Bayes’ Theorem is fundamental for updating probabilities based on evidence.

📊 Naive Bayes Classifier is a simple yet powerful tool for classification.

🤖 Bayesian statistics plays a key role in machine learning and decision-making.

🏆 Bayesian optimization is useful for hyperparameter tuning and A/B testing.

Next: Calculus and Optimization

Next up is calculus, where we’ll get to the very heart of ML.

Footnotes


  1. Cassie Kozyrkov’s blog post & video Statistics: Are you Bayesian or Frequentist? ↩︎ ↩︎

Comments (0)

No comments yet.