fishiwhj
fishiwhj

Reputation: 849

Generate samples from a random matrix

Assume we have a random matrix A of size n*m. Each elements A_ij is the success probability of a Bernoulli distribution.

I want to draw a sample z from A with the following rule:

z_ij draw from Bernoulli(A_ij)

Is there any numpy function support this?

EDIT: operations such as

arr = numpy.random.random([10, 5])
f = lambda x: numpy.random.binomial(1, x)
sp = map(f, arr)

are inefficient. Is there any faster method?

Upvotes: 1

Views: 399

Answers (1)

MSeifert
MSeifert

Reputation: 152587

You can directly give an array as one of the arguments of your binomial distribution, for example:

import numpy as np
arr = np.random.random([10, 5])
sp = np.random.binomial(1, arr)
sp

gives

array([[0, 0, 0, 0, 0],
       [1, 0, 0, 1, 1],
       [1, 0, 1, 0, 0],
       [0, 0, 0, 1, 0],
       [0, 0, 0, 0, 1],
       [0, 1, 0, 1, 0],
       [0, 1, 1, 0, 0],
       [0, 0, 0, 1, 1],
       [0, 1, 0, 0, 0],
       [1, 0, 0, 1, 0]])

Upvotes: 2

Related Questions