Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 5: Bayes’ Theorem and Independence

Exercise 5.1: Implementing Bayes’ Theorem for Disease Test

Let’s verify the disease test calculation using Python. Define variables for the prior probability, sensitivity, and specificity, then implement the calculation for P(D∣Pos)P(D|Pos).

Prior P(Disease): 0.0100
Sensitivity P(Pos|Disease): 0.9500
Specificity P(Neg|No Disease): 0.9500
False Positive Rate P(Pos|No Disease): 0.0500
------------------------------
Overall P(Pos): 0.0590
Posterior P(Disease|Pos): 0.1610
------------------------------
Overall P(Neg): 0.9410
Posterior P(Disease|Neg): 0.0005
Posterior P(No Disease|Neg) = 0.9995

Exercise 5.2: Simulating Bayesian Updates

Let’s simulate the disease test scenario to build intuition. We’ll create a population reflecting the disease prevalence, simulate their test results based on sensitivity/specificity, and then calculate the conditional probability directly from the simulated data.

   Has_Disease  Tests_Positive
0        False           False
1        False           False
2        False           False
3        False           False
4        False           False

--- Simulation Results ---
Population Size: 1000000
Number Actually Diseased: 10039
Number Actually Healthy: 989961
Number Testing Positive: 58926
  - True Positives: 9568
  - False Positives: 49358
------------------------------
Simulated P(Disease | Positive): 0.1624
Theoretical P(Disease | Positive): 0.1610

As the population_size increases, the simulated probability should converge to the theoretical probability calculated using Bayes’ Theorem. This demonstrates how the theorem accurately reflects the underlying frequencies in a large population.

Exercise 5.3: Testing Independence from Data

Let’s simulate rolling two fair dice and check if the events “first die is even” and “sum is 7” are independent.

Theoretical Check: Is P(A∩B)=P(A)P(B)P(A \cap B) = P(A)P(B)? 1/12=?(1/2)×(1/6)1/12 \stackrel{?}{=} (1/2) \times (1/6) 1/12=1/121/12 = 1/12. Yes, they are theoretically independent.

Now, let’s check using simulation.

   Die1  Die2  Sum      A      B
0     1     1    2  False  False
1     5     4    9  False  False
2     5     1    6  False  False
3     3     3    6  False  False
4     4     5    9   True  False

--- Independence Check from Simulation ---
Simulated P(A): 0.5014 (Theoretical: 0.5000)
Simulated P(B): 0.1658 (Theoretical: 0.1667)
Simulated P(A intersect B): 0.0840 (Theoretical: 0.0833)
------------------------------
P(A) * P(B) = 0.0831
Is P(A intersect B) approx equal to P(A) * P(B)? Yes

Simulated P(A|B): 0.5065
Is P(A|B) approx equal to P(A)? Yes

The simulation results should be close to the theoretical values, confirming the independence of these events. Small discrepancies are expected due to random sampling variation.