Module 2 · Beginner · Before you start: the Python and maths you need

Probability for machine learning

Probability for machine learning: conditional probability, Bayes' theorem with a worked example, distributions and model probabilities.

By theprogrammers team · · 8 min read

Machine learning models almost never say "this email is spam". They say "this email is 92% likely to be spam". Weather apps say "70% chance of rain". Fraud systems give every transaction a risk score. Behind all of these is probability: the maths of uncertainty.

This lesson covers the probability ideas you need for machine learning, with no heavy formulas: basic and conditional probability, Bayes' theorem with a surprising medical-test example, the common distributions, and how to use the probabilities your models output.

Probability basics

A probability is a number from 0 (impossible) to 1 (certain) describing how likely something is. It's often written as a percentage: 0.25 is 25%.

For equally likely outcomes:

P(event) = favourable outcomes ÷ total outcomes

The probability of rolling a 6 on a fair die is 1/6, about 0.167. You can check it by simulation, a technique data scientists use all the time when the maths gets hard:

import numpy as np

rng = np.random.default_rng(0)
rolls = rng.integers(1, 7, size=100_000)    # 100,000 dice rolls
print((rolls == 6).mean().round(3))          # 0.165: close to 1/6

Three rules cover most situations:

  • NOT: P(not A) = 1 − P(A). If there's a 30% chance of rain, there's a 70% chance of no rain.
  • AND, for independent events: P(A and B) = P(A) × P(B). Two heads in a row: 0.5 × 0.5 = 0.25.
  • OR, for events that can't both happen: P(A or B) = P(A) + P(B). Rolling a 1 or a 2: 1/6 + 1/6 = 1/3.

Independent means one event doesn't change the chance of the other, like two separate coin tosses.

The full lessons are what is probability?, outcomes, events and sample spaces, rules of probability, permutations and combinations and simulate probability with Python.

Conditional probability: "given that..."

Most interesting questions are conditional: what's the probability of A, given that we know B? It's written P(A | B).

Say a company has 1,000 emails: 200 are spam, and 150 of those spam emails contain the word "free". Among the 800 genuine emails, 40 contain "free".

  • P(spam) = 200 / 1000 = 0.2
  • P("free" | spam) = 150 / 200 = 0.75
  • P(spam | "free") = 150 / (150 + 40) ≈ 0.79

Knowing the email contains "free" raises the probability that it's spam from 20% to 79%. This is exactly what a classifier does: it updates the probability of each class given the features it sees.

Notice that P("free" | spam) = 0.75 and P(spam | "free") = 0.79 are different questions with different answers. Mixing them up is one of the most common reasoning errors in everyday life, and Bayes' theorem connects them.

Bayes' theorem

The full lessons are conditional probability explained, tree diagrams, Bayes' theorem explained and Bayes in practice: medical tests and spam filters.

Bayes' theorem tells you how to flip a conditional probability around:

P(A | B) = P(B | A) × P(A) ÷ P(B)

In words: updated belief = how well the evidence fits × prior belief ÷ how common the evidence is.

  • Prior, P(A): what you believed before seeing the evidence.
  • Likelihood, P(B | A): how likely the evidence is if A is true.
  • Posterior, P(A | B): your updated belief after the evidence.

A worked example that surprises everyone

A disease affects 1% of people. A test for it is quite good:

  • If you have the disease, it's positive 95% of the time.
  • If you don't, it's still (wrongly) positive 5% of the time.

You test positive. What's the chance you actually have the disease? Most people guess about 95%. Let's calculate:

p_disease = 0.01
p_pos_if_disease = 0.95
p_pos_if_healthy = 0.05

p_pos = p_disease * p_pos_if_disease + (1 - p_disease) * p_pos_if_healthy
p_disease_if_pos = p_disease * p_pos_if_disease / p_pos
print(round(p_disease_if_pos, 3))    # 0.161

Only about 16%. Picture 10,000 people: 100 have the disease and 95 of them test positive. Of the 9,900 healthy people, 5%, which is 495, also test positive. So of the 590 positive tests, only 95 are real: 16%.

A tree of 10,000 people. 100 are ill and 95 of them test positive. 9,900 are healthy and 495 of them test positive. Of the 590 positive tests, only 95, about 16%, come from people who are really ill.

The disease is so rare that false alarms from the huge healthy group outnumber the true cases. This is the base rate effect, and it matters enormously in ML: when you build a fraud or disease detector for a rare event, most of its alerts can be false alarms even if it's "95% accurate". You'll meet this again as precision in model evaluation.

Naive Bayes: Bayes' theorem as a classifier

The Naive Bayes classifier applies Bayes' theorem to every word in an email, assuming (naively) that words are independent of each other given the class. The assumption isn't really true, since "free" and "offer" often appear together, but it works surprisingly well, trains in milliseconds and was the classic spam filter for years. It's still a strong baseline for text classification.

Distributions you'll meet

A probability distribution describes how likely each possible outcome is.

DistributionDescribesML example
BernoulliOne yes/no trial with probability pWill this user click: yes or no?
BinomialNumber of successes in n yes/no trialsHow many of 10 customers will buy?
UniformAll outcomes equally likelyRandom initial values, a fair die
Normal (Gaussian)Bell curve around a meanMeasurement errors, heights; many models assume normal noise
PoissonCount of events in a fixed timeOrders per hour, website visits per minute

For example, the probability of exactly 7 heads in 10 fair coin tosses is a binomial calculation:

from math import comb

print(round(comb(10, 7) * 0.5 ** 10, 4))    # 0.1172: about 12%

Expected value

The expected value is the long-run average outcome, weighting each outcome by its probability. A game costs ₹10, and you win ₹50 with probability 0.1:

Expected value = 0.1 × 50 − 10 = −₹5 per game

On average you lose ₹5 a game. Businesses use expected value to turn model probabilities into decisions, such as whether the expected cost of fraud is worth blocking a transaction.

Using the probabilities your model outputs

scikit-learn classifiers have predict_proba, which returns a probability for each class, and predict, which picks a class using a default threshold of 0.5:

Download the data: spambase.csv (1.1 MB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("spambase.csv").

from sklearn.datasets import fetch_openml
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = fetch_openml(data_id=44, as_frame=True, return_X_y=True)   # Spambase: 4,601 emails
y = y.astype(int)                                                  # 1 = spam, 0 = not spam
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X, y)

probs = model.predict_proba(X[:3])
print(probs.round(3))
[[0.415 0.585]
 [0.018 0.982]
 [0.    1.   ]]

Each row is [P(not spam), P(spam)] for one email, and adds up to 1. All three emails are spam. The model is certain about the third, 98.2% sure about the second, but only 58.5% sure about the first: with the default threshold of 0.5 it's still called spam, but only just.

You don't have to use 0.5. Sending a real email to the spam folder is worse than letting one spam through, so a spam filter might move an email only when P(spam) is above 0.9, accepting more spam in the inbox to lose fewer real emails. For disease screening it's the opposite: you might flag anyone with even a 20% chance, accepting more false alarms to miss fewer real cases. Choosing the threshold is a business decision, not just a maths one.

Key takeaways

  • Probability measures uncertainty from 0 to 1; simulation is a handy way to check it.
  • Conditional probability P(A | B) is the probability of A given B, and P(A | B) ≠ P(B | A).
  • Bayes' theorem updates a prior belief with evidence; base rates matter hugely for rare events.
  • Naive Bayes is a fast classifier built directly on Bayes' theorem.
  • Classifiers output probabilities; the threshold you choose trades false alarms against misses.

Practice

  1. A bag has 3 red and 7 blue balls. You draw one, put it back, and draw again. What's the probability both are red?
Show the answer

The draws are independent because you replace the ball: 0.3 × 0.3 = 0.09, or 9%.

  1. In a class, 40% of students play cricket. Of the cricket players, 25% also play chess. What's the probability that a random student plays both?
Show the answer

P(cricket and chess) = P(cricket) × P(chess | cricket) = 0.4 × 0.25 = 0.1, or 10%.

  1. Redo the medical-test example, but for a disease that affects 10% of people. How does the answer change?
Show the answer
p_d = 0.10
p_pos = p_d * 0.95 + (1 - p_d) * 0.05
print(round(p_d * 0.95 / p_pos, 3))    # 0.679

About 68%. When the condition is more common, a positive test is far more meaningful. The test didn't change; the base rate did.

  1. Simulate 100,000 rolls of two dice and estimate the probability that they add up to 7. The exact answer is 6/36.
Show the answer
rng = np.random.default_rng(1)
a = rng.integers(1, 7, size=100_000)
b = rng.integers(1, 7, size=100_000)
print(((a + b) == 7).mean())    # 0.1645: close to 6/36 ≈ 0.167

Interview questions

Explain Bayes' theorem with an example.

P(A | B) = P(B | A) P(A) / P(B). It updates the probability of a hypothesis A after seeing evidence B. For example, with a 1% disease rate, a test that is 95% sensitive and has a 5% false positive rate gives only about a 16% chance of disease after a positive result, because false positives from the large healthy population dominate.

Why is Naive Bayes called "naive"?

It assumes all features are conditionally independent given the class, for example that each word in an email appears independently of the others. The assumption is rarely true, but the classifier often works well anyway, especially for text.

What is the difference between independent and mutually exclusive events?

Independent events don't affect each other's probability: P(A and B) = P(A) × P(B). Mutually exclusive events can't happen together: P(A and B) = 0. Two events with non-zero probability can't be both.

What is the difference between predict and predict_proba in scikit-learn?

predict_proba returns the estimated probability of each class. predict returns a class label, by default the class with the highest probability, which for binary problems is a 0.5 threshold. Using predict_proba lets you choose your own threshold.

What to learn next

  1. Learn how models improve themselves with calculus for machine learning.
  2. Revisit the decision-threshold idea in the machine learning workflow.