有没有办法在python中使用numpy或scipy来计算多项式PMF?这里描述了PMF:https://en.wikipedia.org/wiki/Multinomial_distribution
scipy.stats.binom仅适用于二项式随机变量。
答案 0 :(得分:1)
虽然it might be available in the future version (0.18 or up)已经在scipy中没有多项分布。
同时,你可以很容易地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为零。
答案 1 :(得分:0)
scipy中没有提供Multiomial PMF功能。但是,您可以自己使用numpy.random.multinomial类来绘制样本。