Section 3.1 PMFs
A
Pmf object is like a FreqTab that contains probabilities instead of frequencies. So one way to make a Pmf is to start with a FreqTab. For example, hereβs a FreqTab that represents the distribution of values in a short sequence.
$ from empiricaldist import FreqTab
ftab = FreqTab.from_seq([1, 2, 2, 3, 5])
ftab
1 1
2 2
3 1
5 1
Name: , dtype: int64
The sum of the frequencies is the size of the original sequence.
$ n = ftab.sum()
n
np.int64(5)
If we divide the frequencies by
n, they represent proportions, rather than counts.
$ pmf = ftab / n
pmf
1 0.2
2 0.4
3 0.2
5 0.2
Name: , dtype: float64
This result indicates that 20% of the values in the sequence are 1, 40% are 2, and so on.
We can also think of these proportions as probabilities in the following sense: if we choose a random value from the original sequence, the probability we choose the value 1 is 0.2, the probability we choose the value 2 is 0.4, and so on.
Because we divided through by
n, the sum of the probabilities is 1, which means that this distribution is normalized.
$ pmf.sum()
np.float64(1)
A normalized
FreqTab object represents a probability mass function (PMF), so-called because probabilities associated with discrete values are also called "probability masses".
The
empiricaldist library provides a Pmf object that represents a probability mass function, so instead of creating a FreqTab object and then normalizing it, we can create a Pmf object directly.
$ from empiricaldist import Pmf
pmf = Pmf.from_seq([1, 2, 2, 3, 5])
pmf
1 0.2
2 0.4
3 0.2
5 0.2
Name: , dtype: float64
The
Pmf is normalized so the total probability is 1.
$ pmf.sum()
np.float64(0.8500000000000001)
Pmf and FreqTab objects are similar in many ways. To look up the probability associated with a value, we can use the bracket operator.
$ pmf[2]
np.float64(0.4)
Or use parentheses to call the
Pmf like a function.
$ pmf(2)
np.float64(0.4)
To assign a probability to a value, you have to use the bracket operator.
$ pmf[2] = 0.2
pmf(2)
np.float64(0.2)
You can modify an existing
Pmf by incrementing the probability associated with a value:
$ pmf[2] += 0.3
pmf[2]
np.float64(0.5)
Or you can multiply a probability by a factor:
$ pmf[2] *= 0.5
pmf[2]
np.float64(0.25)
If you modify a
Pmf, the result may not be normalized β that is, the probabilities may no longer add up to 1.
$ pmf.sum()
np.float64(0.8500000000000001)
The
normalize method renormalizes the Pmf by dividing through by the sum β and returning the sum.
$ pmf.normalize()
np.float64(0.8500000000000001)
Pmf objects provide a copy method so you can make and modify a copy without affecting the original.
$ pmf.copy()
1 0.235294
2 0.294118
3 0.235294
5 0.235294
Name: , dtype: float64
Like a
FreqTab object, a Pmf object has a qs attribute that accesses the quantities and a ps attribute that accesses the probabilities. It also has a bar method that plots the Pmf as a bar graph and a plot method that plots it as a line graph.
