Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 20 min · revision 2

Conditional Probability and the Base-Rate Trap

Treat counts as random variables with an expectation and a variance, read conditional probabilities off a count table, use Bayes' rule with the base rate to turn a detector's recall and false-positive rate into its precision, and see on a trained classifier why precision falls when the positive class gets rarer while recall stays put.

Contentsand lesson path

What you will learn

  • Apply conditional probability and Bayes' rule to compute posterior probabilities, such as the precision of a detector on a rare class.

01. Why it matters

A factory installs a camera that checks every part on a production line. The supplier's test report says it catches 95% of defective parts and wrongly flags only 2% of good ones. After a week the inspectors complain: four out of five flagged parts they check are fine. Nobody made a mistake and the camera works as specified. The inspectors met the base rate: only 0.5% of parts are defective, so even a small false-alarm rate on the huge number of good parts produces more flags than the few real defects do.

The same arithmetic decides how useful a fraud model, a spam filter or a medical screening test is. This lesson builds it from the ground up: counts as random variables, conditional probability, Bayes' rule, and what happens to precision and recall when the share of positives changes. The examples were tested with Python 3.12, NumPy 2.5, pandas 3.1 and scikit-learn 1.9.

02. Random variables, expectation and variance

A random variable is a number whose value depends on chance. Let X be 1 if a part is defective and 0 if it is good. X follows a Bernoulli distribution with P(X = 1) = p, here p = 0.005. Its expectation E[X], the long-run average, is the sum of each value times its probability: 1 × p + 0 × (1 − p) = p. Its variance, the expected squared distance from the mean, is p(1 − p).

Count the defects in a shift of n = 10,000 independent parts and you get a new random variable: the sum of 10,000 Bernoulli variables, which follows a binomial distribution. Expectations add, so the expected count is n × p = 50. For independent variables the variances add too, giving n × p × (1 − p) = 49.75, and a standard deviation (the square root of the variance) of about 7. The script checks the formulas by simulating 20,000 shifts.

Python · expectation.py
"""Defective parts per shift as a random variable: formula versus simulation."""
import numpy as np

n, p = 10_000, 0.005  # parts per shift, probability that one part is defective
mean = n * p  # expectation of a binomial count
var = n * p * (1 - p)  # variance of a binomial count
print(f"formula:   mean {mean:.2f}  variance {var:.2f}  sd {var ** 0.5:.2f}")

rng = np.random.default_rng(5)
shifts = rng.binomial(n, p, size=20_000)  # 20,000 simulated shifts
print(f"simulated: mean {shifts.mean():.2f}  variance {shifts.var():.2f}  "
      f"sd {shifts.std():.2f}")
print(f"shifts with more than 60 defects: {(shifts > 60).mean():.1%}")
Expected output
formula:   mean 50.00  variance 49.75  sd 7.05
simulated: mean 49.98  variance 49.35  sd 7.02
shifts with more than 60 defects: 7.1%

The simulation agrees with the formulas, and it shows something the mean hides: 7.1% of shifts have more than 60 defects although nothing changed in the process. Counts of rare events fluctuate by roughly the square root of their mean, so a jump from 50 to 60 is not yet evidence of a problem. Keep this in mind for evaluation: a test set with 50 positives gives a noisy estimate of any metric that depends on them, which lesson 4 measures directly.

03. Conditional probability from a count table

The conditional probability of A given B, written P(A | B), is the probability of A when you only look at the cases where B happened:

  • P(A | B) = P(A and B) / P(B)

With counts, that means: take the rows where B is true, and find the share of them where A is also true. The script simulates 200,000 parts passing the camera and builds a count table with pd.crosstab.

Python · counts.py
"""Simulate a camera that inspects parts, then read probabilities off the counts."""
import numpy as np
import pandas as pd

rng = np.random.default_rng(11)
n = 200_000
defect = rng.random(n) < 0.005  # 0.5% of parts are defective
# The camera flags 95% of defective parts and 2% of good ones.
flag = np.where(defect, rng.random(n) < 0.95, rng.random(n) < 0.02)

table = pd.crosstab(pd.Series(defect, name="defect"), pd.Series(flag, name="flag"))
print(table, end="\n\n")

p_flag_given_defect = (flag & defect).sum() / defect.sum()
p_defect_given_flag = (flag & defect).sum() / flag.sum()
print(f"P(flag | defect) = {p_flag_given_defect:.3f}")
print(f"P(defect | flag) = {p_defect_given_flag:.3f}")
Expected output
flag     False  True
defect
False   195028   3968
True        45    959

P(flag | defect) = 0.955
P(defect | flag) = 0.195

Both numbers come from the same 959 parts that are defective and flagged, divided by different totals. P(flag | defect) divides by the 1,004 defective parts and is 0.955. P(defect | flag) divides by the 4,927 flagged parts and is only 0.195. The two conditionals answer different questions, and swapping them is the core of the base-rate trap.

Each has a name in machine learning, with "positive" meaning the class you want to detect:

  • Recall (also called sensitivity or true-positive rate) is P(flag | positive): the share of real positives the model catches.
  • The false-positive rate (FPR) is P(flag | negative): the share of negatives wrongly flagged. Its complement, 1 − FPR, is the specificity.
  • Precision is P(positive | flag): the share of flags that are real. It is the number the inspectors experience.

04. Bayes' rule and the base rate

You can write P(defect and flag) in two ways: P(flag | defect) × P(defect), or P(defect | flag) × P(flag). Setting them equal and dividing by P(flag) gives Bayes' rule:

  • P(defect | flag) = P(flag | defect) × P(defect) / P(flag)

P(defect) is the prior, also called the base rate or prevalence: what you believe before seeing the flag. P(flag | defect) is the likelihood of the evidence for a defective part. P(flag) is the overall flag rate, which the law of total probability splits into the two ways a flag can happen: P(flag | defect) × P(defect) + P(flag | good) × P(good). The result, P(defect | flag), is the posterior: your belief after the flag.

The same rule reverses any conditional, not only detector questions. Suppose 30% of support tickets mention a refund, 50% of all tickets are urgent, and 40% of refund tickets are urgent. Then P(refund | urgent) = 0.4 × 0.3 / 0.5 = 0.24: about a quarter of urgent tickets mention a refund.

For detectors, natural frequencies make the rule easy to check by hand. In 10,000 parts at a 0.5% defect rate there are 50 defective parts, of which 95% (47.5) are flagged, and 9,950 good parts, of which 2% (199) are flagged. Precision is 47.5 / (47.5 + 199) = 0.193. The script repeats this for several defect rates.

Python · bayes.py
"""Bayes' rule for the camera at different defect rates (expected counts per shift)."""


def posterior(prior, recall, fpr):
    """P(defect | flag) from P(defect), P(flag | defect) and P(flag | good)."""
    evidence = recall * prior + fpr * (1 - prior)  # P(flag), total probability
    return recall * prior / evidence


recall, fpr, parts = 0.95, 0.02, 10_000
print(f"{'defect rate':>11} {'true flags':>11} {'false flags':>12} {'precision':>10}")
for prior in [0.001, 0.005, 0.02, 0.10, 0.50]:
    true_flags = parts * prior * recall  # expected value of a count
    false_flags = parts * (1 - prior) * fpr
    print(f"{prior:>11.1%} {true_flags:>11.1f} {false_flags:>12.1f} "
          f"{posterior(prior, recall, fpr):>10.3f}")
Expected output
defect rate  true flags  false flags  precision
       0.1%         9.5        199.8      0.045
       0.5%        47.5        199.0      0.193
       2.0%       190.0        196.0      0.492
      10.0%       950.0        180.0      0.841
      50.0%      4750.0        100.0      0.979

The camera is identical in every row. The number of false flags hardly moves (from 199.8 down to 100), because it depends on the good parts, and there are always thousands of them. The true flags grow with the defect rate. So precision runs from 4.5% at a 0.1% defect rate to 97.9% when half the parts are bad. When the positive class is rare, the false-positive rate, not recall, decides how useful the flags are: halving the FPR to 1% would raise precision at 0.5% from 0.193 to about 0.32, while raising recall from 95% to 100% would barely change it.

05. Precision and recall when prevalence shifts

Recall only looks at positives and the FPR only looks at negatives, so neither depends on how many positives there are. Precision mixes both groups, so it does. You can see this with a trained model. The script trains a logistic regression on synthetic data, then scores it on three test sets that share the same 10,000 negatives and differ only in how many positives are added.

Python · shift.py
"""Score one trained classifier on test sets that differ only in prevalence."""
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_score, recall_score

X, y = make_classification(n_samples=60_000, n_features=8, n_informative=4,
                           n_clusters_per_class=1, class_sep=0.6,
                           random_state=0)  # about half the rows are positive
model = LogisticRegression().fit(X[:20_000], y[:20_000])
X_pool, y_pool = X[20_000:], y[20_000:]
pos, neg = np.flatnonzero(y_pool == 1), np.flatnonzero(y_pool == 0)

rng = np.random.default_rng(0)
print(f"{'prevalence':>10} {'recall':>7} {'FPR':>6} {'precision':>10} {'Bayes':>6}")
for prevalence in [0.50, 0.10, 0.01]:
    n_pos = round(10_000 * prevalence / (1 - prevalence))
    rows = np.concatenate([neg[:10_000], rng.choice(pos, n_pos, replace=False)])
    pred, truth = model.predict(X_pool[rows]), y_pool[rows]
    rec = recall_score(truth, pred)
    fpr = pred[truth == 0].mean()  # share of the negatives that were flagged
    bayes = rec * prevalence / (rec * prevalence + fpr * (1 - prevalence))
    print(f"{prevalence:>10.0%} {rec:>7.3f} {fpr:>6.3f} "
          f"{precision_score(truth, pred):>10.3f} {bayes:>6.3f}")
Expected output
prevalence  recall    FPR  precision  Bayes
       50%   0.931  0.061      0.939  0.939
       10%   0.929  0.061      0.630  0.630
        1%   0.921  0.061      0.133  0.133

Recall stays near 0.93; it moves a little only because each test set draws different positives, and the 1% set has just 101 of them. The FPR is exactly the same because the negatives are the same. Precision falls from 0.939 to 0.133, and the Bayes column, computed from recall, FPR and prevalence alone, matches it to three decimals. Precision is not a fixed property of the model: it belongs to the model and the population it runs on.

This has practical consequences. A validation set balanced by down-sampling the majority class reports a precision that production will not reach, so report the prevalence with every precision figure, or recompute precision for the deployment prevalence with Bayes' rule. The argument assumes that only the share of positives changes while each class looks the same as before. If the positives themselves change, for example fraudsters adopt new patterns, recall changes too and you need fresh labelled data.

06. Check your understanding

Practice check · 3 questions

Conditionals, base rates and counts

Work each one out before you look at the options. Each question has one best answer.

Q1. A moderation classifier was evaluated on a balanced set (50% abusive posts): recall 0.80 and false-positive rate 0.05. In production 2% of posts are abusive, and abusive posts look the same as before. Roughly what share of flagged production posts will be abusive?
Q2. This function should return P(defect | flag). What is wrong with it? def p_defect_given_flag(prior, recall, fpr): return recall * prior / (recall * prior + fpr * prior)
Q3. A payment check wrongly flags each legitimate payment with probability 0.01, independently. A shop has 2,000 legitimate payments a day. What are the expected number and the standard deviation of false alarms per day?
Practice only: not graded, not saved, not evidence.

07. Apply it

Use the two classifiers from this skill's practice task:

  1. From each model's confusion matrix on the test set, compute recall, false-positive rate and precision, and note the prevalence of the test set.
  2. With posterior() from bayes.py, recompute each model's precision for a prevalence of half and a tenth of the test-set value. Check that the formula reproduces the measured precision at the test-set prevalence.
  3. Write two sentences: which model loses more precision as positives get rarer, and whether its recall or its false-positive rate explains that.

08. Review prompt

Without looking back:

  1. What are the expectation and the variance of a binomial count, and why do counts of rare events fluctuate so much?
  2. How do you read P(A | B) off a count table, and why is P(flag | defect) not P(defect | flag)?
  3. Write Bayes' rule and name each part. Work out a posterior with natural frequencies.
  4. Which of recall, false-positive rate and precision change when the positive class becomes rarer, and under what assumption?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check