4.9 KiB
Events happen or do not happen. Things exist or do not. Probability is how we think about these.
Thie notebook is based on the original here (linked from this excellent page).
Probability as logic using Python's data model¶
In this short notebook we'll show how probability really is just an extension of boolean logic. We'll make a class P
, that uses Python's data model methods to implement a working example of probability as logic using -
,&
and |
.
class P:
"""
Example of Probability as logic using Python's data model
In this simple example these probabilites are assumed to
be conditionally independent.
"""
def __init__(self,prob):
assert prob >= 0, "probabilities can't be negative!"
assert prob <= 1, "probabilities can't be greater than 1!"
self.prob = prob
def __repr__(self):
return "P({})".format(self.prob)
def __neg__(self):
return P(1-self.prob)
def __and__(self,P2):
return P(self.prob * P2.prob)
def __or__(self,P2):
return P(self.prob + P2.prob - (self & P2).prob)
P(0.5)
P(0.5) & P(0.5)
True & True
P(0.5) | P(0.5)
We can then use this to work out probabilities of various events happening using python!
Suppose, for example, you know that there is a 0.3 probability of rain tomorrow and you'll get rained on if you forget your umbrella or your umbrella is broken. Then let's say you forget your umbrella with a probability 0.1 and you think your umbrella might be the broken, we'll give that a probability of 0.7.
Now let's use logic to answer: What's the probability you will not get wet?
Let's start with our facts:
rain = P(0.3)
forget = P(0.1)
broken = P(0.7)
The probability of being wet
is:
wet = rain & (forget | broken)
wet
and logically the probability of being dry is:
-wet
With probability as logic, no matter how complicated our reasoning, we can now trivially code up a solution in Python!
Conclusions¶
- Probabilities are intuitive
- Do not let mathematical notation of probabilities scare you
- Working mathematically and computationally with probabilities can be very useful