[英]how to calculate probability mass function for multinomial in scipy?
有没有一种方法可以使用numpy或scipy在python中计算多项式PMF? 此处描述了PMF: https : //en.wikipedia.org/wiki/Multinomial_distribution
scipy.stats.binom仅适用于二项式随机变量。
尽管scipy中没有多项式分布,但在将来的版本(0.18或更高版本)中可能可用 。
同时,您可以相当轻松地进行DIY:
def logpmf(self, x, n, p):
"""Log of the multinomial probability mass function.
Parameters
----------
x : array_like
Quantiles.
n : int
Number of trials
p : array_like, shape (k,)
Probabilities. These should sum to one. If they do not, then
``p[-1]`` is modified to account for the remaining probability so
that ``sum(p) == 1``.
Returns
-------
logpmf : float
Log of the probability mass function evaluated at `x`.
"""
x = np.asarray(x)
if p.shape[0] != x.shape[-1]:
raise ValueError("x & p shapes do not match.")
coef = gammaln(n + 1) - gammaln(x + 1.).sum(axis=-1)
val = coef + np.sum(xlogy(x, p), axis=-1)
# insist on that the support is a set of *integers*
mask = np.logical_and.reduce(np.mod(x, 1) == 0, axis=-1)
mask &= (x.sum(axis=-1) == n)
out = np.where(mask, val, -np.inf)
return out
这里gammaln
是scipy.special.gammaln
, xlogy
是scipy.special.xlogy
。 如您所见,主要工作是确保非整数值的pmf为零。
scipy中没有提供多项式PMF函数。 但是,您可以自己使用numpy.random.multinomial类绘制样本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.