如何绘制样本的PMF?

8 投票
4 回答
21982 浏览
提问于 2025-04-18 17:03

有没有什么函数或者库可以帮助我绘制样本的概率质量函数,就像绘制样本的概率密度函数那样简单?

比如,使用pandas绘制概率密度函数(PDF)只需要简单地调用一下:

sample.plot(kind="density")

如果没有简单的方法,那我该怎么计算概率质量函数(PMF),然后用matplotlib来绘制呢?

4 个回答

0
import matplotlib.pyplot as plt
import seaborn as sns
samp = [5, 2, 2, 1, 2, 8, 6, 7, 5, 3, 2, 6, 4, 9, 7, 6, 4, 7, 6, 8, 7, 0, 6,
       2, 9, 8, 7, 7, 2, 6, 2, 8, 0, 2, 5, 1, 3, 6, 7, 7, 2, 2, 0, 3, 8, 7,
       4, 0, 5, 7, 5, 4, 4, 9, 5, 1, 6, 6, 0, 9, 4, 2, 0, 8, 7, 5, 1, 1, 2,
       8, 3, 8, 9, 0, 0, 6, 8, 7, 2, 6, 7, 9, 7, 8, 8, 3, 3, 7, 8, 2, 2, 4,
       4, 5, 3, 4, 1, 5, 5, 1]

plt.ylabel('PMF')
sns.histplot(samp, stat='probability', bins=20);

在这里输入图片描述

0

你可以使用 np.histogram 来计算概率质量函数(PMF),只要你设置 density=true,并且确保使用的每个区间(bins)宽度都是1(否则你得到的可能是概率密度函数的值,这通常不是你想要的结果)。

>>> xs = np.array(
          [5, 2, 2, 1, 2, 8, 6, 7, 5, 3, 2, 6, 4, 9, 7, 6, 4, 7, 6, 8, 7, 0, 6,
           2, 9, 8, 7, 7, 2, 6, 2, 8, 0, 2, 5, 1, 3, 6, 7, 7, 2, 2, 0, 3, 8, 7,
           4, 0, 5, 7, 5, 4, 4, 9, 5, 1, 6, 6, 0, 9, 4, 2, 0, 8, 7, 5, 1, 1, 2,
           8, 3, 8, 9, 0, 0, 6, 8, 7, 2, 6, 7, 9, 7, 8, 8, 3, 3, 7, 8, 2, 2, 4,
           4, 5, 3, 4, 1, 5, 5, 1])

>>> pmf, bins = np.histogram(xs, bins=range(0,11), density=True)
>>> np.column_stack((bins[:-1], pmf))
array([[ 0.  ,  0.08],
       [ 1.  ,  0.07],
       [ 2.  ,  0.15],
       [ 3.  ,  0.07],
       [ 4.  ,  0.09],
       [ 5.  ,  0.1 ],
       [ 6.  ,  0.11],
       [ 7.  ,  0.15],
       [ 8.  ,  0.12],
       [ 9.  ,  0.06]])
3

给定一个Pandas数据框,df,你可以使用seaborn来写:

import seaborn as sns

probabilities = df['SomeColumn'].value_counts(normalize=True)    
sns.barplot(probabilities.index, probabilities.values)
16

如果ts是一个序列,你可以通过以下方式获取样本的概率质量函数(PMF):

>>> pmf = ts.value_counts().sort_index() / len(ts)

然后可以通过以下方式绘制它:

>>> pmf.plot(kind='bar')

如果只使用numpy的话,可以通过np.unique来实现:

>>> xs = np.random.randint(0, 10, 100)
>>> xs
array([5, 2, 2, 1, 2, 8, 6, 7, 5, 3, 2, 6, 4, 9, 7, 6, 4, 7, 6, 8, 7, 0, 6,
       2, 9, 8, 7, 7, 2, 6, 2, 8, 0, 2, 5, 1, 3, 6, 7, 7, 2, 2, 0, 3, 8, 7,
       4, 0, 5, 7, 5, 4, 4, 9, 5, 1, 6, 6, 0, 9, 4, 2, 0, 8, 7, 5, 1, 1, 2,
       8, 3, 8, 9, 0, 0, 6, 8, 7, 2, 6, 7, 9, 7, 8, 8, 3, 3, 7, 8, 2, 2, 4,
       4, 5, 3, 4, 1, 5, 5, 1])

>>> val, cnt = np.unique(xs, return_counts=True)
>>> pmf = cnt / len(xs)

>>> # values along with probability mass function
>>> np.column_stack((val, pmf))
array([[ 0.  ,  0.08],
       [ 1.  ,  0.07],
       [ 2.  ,  0.15],
       [ 3.  ,  0.07],
       [ 4.  ,  0.09],
       [ 5.  ,  0.1 ],
       [ 6.  ,  0.11],
       [ 7.  ,  0.15],
       [ 8.  ,  0.12],
       [ 9.  ,  0.06]])

撰写回答