Python / Numpy / Scipy: draw random Poisson values ​​with different lambdas

My problem is to extract the most efficient way of N random Poisson values ​​( RV), each of which has a different average / speed Lam. Mostly size(RV) == size(Lam).

Here it is a naive (very slow) implementation:

import numpy as NP

def multi_rate_poisson(Lam):
    rv = NP.zeros(NP.size(Lam))
    for i,lam in enumerate(Lam):
        rv[i] = NP.random.poisson(lam=lam, size=1)
    return rv

This, on my laptop, with 1e6 samples gives:

Lam = NP.random.rand(1e6) + 1
timeit multi_poisson(Lam)
1 loops, best of 3: 4.82 s per loop

Can this be improved?

+5
source share
1 answer

Although docstrings do not document this functionality, source indicates that it is possible to pass an array to numpy.random. Poisson function.

>>> import numpy
>>> # 1 dimension array of 1M random var uniformly distributed between 1 and 2
>>> numpyarray = numpy.random.rand(1e6) + 1 
>>> # pass to poisson
>>> poissonarray = numpy.random.poisson(lam=numpyarray)
>>> poissonarray
array([4, 2, 3, ..., 1, 0, 0])

poisson , .

>>> import matplotlib.pyplot
>>> count, bins, ignored = matplotlib.pyplot.hist(
            numpy.random.poisson(
                    lam=numpy.random.rand(1e6) + 10), 
                    14, normed=True)
>>> matplotlib.pyplot.show()

.

>>> timeit.Timer("numpy.random.poisson(lam=numpy.random.rand(1e6) + 1)",
                 'import numpy').repeat(3,1)
[0.13525915145874023, 0.12136101722717285, 0.12127304077148438]
+1

All Articles