How to Apply Bayes' Theorem in Python

By IncludeHelp Last updated : November 26, 2023

Problem statement

Given the values pA, pB, and pBA. You have to write a Python program to apply Bayes' theorem.

What is Bayes' Theorem?

Bayes' Theorem states that for any two events A and B. The probability of occurrence of event A given that event B has occurred.

```P(A|B) = P(A)*P(B|A)/P(B)
```

Where,

• P(A|B) is the probability of occurrence of event A, given that event B has occurred.
• P(B|A) is the probability of occurrence of event B, given that event A has occurred.
• P(A) is the probability of occurrence of event A.
• P(B) is the probability of occurrence of event B.

Example: Applying Bayes' Theorem in Python

```# Python program to apply Baye's theorem
pA = 0.2
pB = 0.4
pBA = 0.85

print("The probability of occurrence of A ", pA)
print("The probability of occurrence of B ", pB)
print("The probability of occurrence of B given A has occurred ", pBA)

pAB = pA * pBA / pB
print("The probability of occurrence of A given B has occurred ", pAB)```

Output

The output of the above program is:

```The probability of occurrence of A  0.2
The probability of occurrence of B  0.4
The probability of occurrence of B given A has occurred  0.85
The probability of occurrence of A given B has occurred  0.425```