|
17 | 17 |
|
18 | 18 | """Namespace for operators used in Gluon dispatched by F=ndarray."""
|
19 | 19 | from __future__ import absolute_import
|
| 20 | +import numpy as np |
20 | 21 | from ...base import numeric_types
|
21 | 22 | from ...context import current_context
|
| 23 | +from ..ndarray import NDArray |
22 | 24 | from . import _internal as _npi
|
23 | 25 |
|
24 |
| -__all__ = ['uniform', 'normal'] |
| 26 | +__all__ = ['uniform', 'normal', 'multinomial'] |
25 | 27 |
|
26 | 28 |
|
27 | 29 | def _random_helper(random, sampler, params, shape, dtype, ctx, out, kwargs):
|
@@ -135,3 +137,40 @@ def normal(loc=0.0, scale=1.0, size=None, **kwargs):
|
135 | 137 | out = kwargs.pop('out', None)
|
136 | 138 | return _random_helper(_npi.random_normal, None,
|
137 | 139 | [loc, scale], size, dtype, ctx, out, kwargs)
|
| 140 | + |
| 141 | + |
| 142 | +def multinomial(n, pvals, size=None): |
| 143 | + """Draw samples from a multinomial distribution. |
| 144 | +
|
| 145 | + The multinomial distribution is a multivariate generalisation of the binomial distribution. |
| 146 | + Take an experiment with one of ``p`` possible outcomes. An example of such an experiment is throwing a dice, |
| 147 | + where the outcome can be 1 through 6. Each sample drawn from the distribution represents n such experiments. |
| 148 | + Its values, ``X_i = [X_0, X_1, ..., X_p]``, represent the number of times the outcome was ``i``. |
| 149 | +
|
| 150 | +
|
| 151 | + Parameters |
| 152 | + ---------- |
| 153 | + n : int |
| 154 | + Number of experiments. |
| 155 | + pvals : sequence of floats, length p |
| 156 | + Probabilities of each of the p different outcomes. These should sum to 1 |
| 157 | + (however, the last element is always assumed to account for the remaining |
| 158 | + probability, as long as ``sum(pvals[:-1]) <= 1)``. |
| 159 | + size : int or tuple of ints, optional |
| 160 | + Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` sam- |
| 161 | + ples are drawn. Default is None, in which case a single value is returned. |
| 162 | +
|
| 163 | + Returns |
| 164 | + ------- |
| 165 | + out : ndarray |
| 166 | + The drawn samples, of shape size, if that was provided. If not, the shape is ``(N,)``. |
| 167 | + In other words, each entry ``out[i,j,...,:]`` is an N-dimensional value drawn from the distribution. |
| 168 | + """ |
| 169 | + if isinstance(pvals, NDArray): |
| 170 | + return _npi.multinomial(pvals, pvals=None, n=n, size=size) |
| 171 | + else: |
| 172 | + if isinstance(pvals, np.ndarray): |
| 173 | + pvals = pvals.tolist() |
| 174 | + if any(isinstance(i, list) for i in pvals): |
| 175 | + raise ValueError('object too deep for desired array') |
| 176 | + return _npi.multinomial(n=n, pvals=pvals, size=size) |
0 commit comments