8000 ENH: Support array-like `n` in random.random.multinomial by ColCarroll · Pull Request #9710 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content

ENH: Support array-like n in random.random.multinomial #9710

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 45 additions & 20 deletions numpy/random/mtrand/mtrand.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -4533,7 +4533,7 @@ cdef class RandomState:
x.shape = tuple(final_shape)
return x

def multinomial(self, npy_intp n, object pvals, size=None):
def multinomial(self, object n, object pvals, size=None):
"""
multinomial(n, pvals, size=None)

Expand All @@ -4549,8 +4549,11 @@ cdef class RandomState:

Parameters
----------
n : int
n : int or array_like of ints
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs .. versionchanged:: 1.14.0 with a note that allowing array_like here is new. You can find examples in the file.

Number of experiments.

.. versionchanged:: 1.14.0
Earlier NumPy versions did not allow array_like ``n``
pvals : sequence of floats, length p
Probabilities of each of the ``p`` different outcomes. These
should sum to 1 (however, the last element is always assumed to
Expand Down Expand Up @@ -4588,6 +4591,19 @@ cdef class RandomState:
For the first run, we threw 3 times 1, 4 times 2, etc. For the second,
we threw 2 times 1, 4 times 2, etc.

Now, do one experiment throwing the dice 10 time, and 10 times again,
and another throwing the dice 20 times, and 20 times again:

>>> np.random.multinomial([10, 20], [1/6.]*6, size=2)
array([[[0, 1, 3, 0, 4, 2],
[1, 6, 0, 2, 1, 0]],

[[4, 5, 4, 2, 2, 3],
[4, 2, 1, 4, 6, 3]]])

The first array shows the outcomes of throwing the dice 10 times, and
the second shows the outcomes from throwing the dice 20 times.

A loaded die is more likely to land on number 6:

>>> np.random.multinomial(100, [1/7.]*5 + [2/7.])
Expand All @@ -4609,40 +4625,49 @@ cdef class RandomState:

"""
cdef npy_intp d
cdef ndarray parr "arrayObject_parr", mnarr "arrayObject_mnarr"
cdef ndarray parr "arrayObject_parr", mnarr "arrayObject_mnarr", narr "arrayObject_narr"
cdef double *pix
cdef long *mnix
cdef npy_intp i, j, dn, sz
cdef npy_intp i, j, k, m, dn, sz
cdef double Sum

narr = <ndarray>PyArray_FROM_OTF(n, NPY_LONG, NPY_ARRAY_ALIGNED)
nix = <long*>PyArray_DATA(narr)

d = len(pvals)
parr = <ndarray>PyArray_ContiguousFromObject(pvals, NPY_DOUBLE, 1, 1)
pix = <double*>PyArray_DATA(parr)

if kahan_sum(pix, d-1) > (1.0 + 1e-12):
raise ValueError("sum(pvals[:-1]) > 1.0")

shape = _shape_from_size(size, d)
if narr.shape == ():
m = 1
shape = _shape_from_size(size, d)
else:
m = len(narr)
shape = (m,) + _shape_from_size(size, d)

multin = np.zeros(shape, int)
mnarr = <ndarray>multin
mnix = <long*>PyArray_DATA(mnarr)
sz = PyArray_SIZE(mnarr)
sz = PyArray_SIZE(mnarr) / m
with self.lock, nogil, cython.cdivision(True):
i = 0
while i < sz:
Sum = 1.0
dn = n
for j from 0 <= j < d-1:
mnix[i+j] = rk_binomial(self.internal_state, dn, pix[j]/Sum)
dn = dn - mnix[i+j]
if dn <= 0:
break
Sum = Sum - pix[j]
if dn > 0:
mnix[i+d-1] = dn

i = i + d
for k in range(m):
i = 0
while i < sz:
Sum = 1.0
dn = nix[k]
for j in range(d - 1):
mnix[k*sz+i+j] = rk_binomial(self.internal_state, dn, pix[j]/Sum)
dn = dn - mnix[k*sz+i+j]
if dn <= 0:
break
Sum = Sum - pix[j]
if dn > 0:
mnix[k*sz+i+d-1] = dn

i = i + d

return multin

Expand Down
14 changes: 11 additions & 3 deletions numpy/random/tests/test_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -650,14 +650,22 @@ def test_logseries(self):

def test_multinomial(self):
np.random.seed(self.seed)
actual = np.random.multinomial(20, [1/6.]*6, size=(3, 2))
size = (3, 2)
actual = np.random.multinomial(20, [1/6.]*6, size=size)
desired = np.array([[[4, 3, 5, 4, 2, 2],
[5, 2, 8, 2, 2, 1]],
[[3, 4, 3, 6, 0, 4],
[2, 1, 4, 3, 6, 4]],
[[4, 4, 2, 5, 2, 3],
[4, 3, 4, 2, 3, 4]]])
assert_array_equal(actual, desired)
assert_equal(actual.squeeze().sum(axis=-1), np.ones(size) * 20)

# Check for iterable n
ns = [20, 40]
actual = np.random.multinomial(ns, [1/6.]*6, size=size)
for n, sample_sum in zip(ns, actual.sum(axis=-1)):
assert_equal(sample_sum, np.ones(size) * n)

def test_multivariate_normal(self):
np.random.seed(self.seed)
Expand Down Expand Up @@ -1106,13 +1114,13 @@ def test_noncentral_f(self):
assert_raises(ValueError, nonc_f, bad_dfnum, dfden, nonc * 3)
assert_raises(ValueError, nonc_f, dfnum, bad_dfden, nonc * 3)
assert_raises(ValueError, nonc_f, dfnum, dfden, bad_nonc * 3)

def test_noncentral_f_small_df(self):
self.setSeed()
desired = np.array([6.869638627492048, 0.785880199263955])
actual = np.random.noncentral_f(0.9, 0.9, 2, size=2)
assert_array_almost_equal(actual, desired, decimal=14)

def test_chisquare(self):
df = [1]
bad_df = [-1]
Expand Down
0