简体   繁体   中英

Using numpy.random.normal with arrays

Suppose i have the following two arrays with means and standard deviations:

mu = np.array([2000, 3000, 5000, 1000])
sigma = np.array([250, 152, 397, 180])

Then:

a = np.random.normal(mu, sigma)

In [1]: a
Out[1]: array([1715.6903716 , 3028.54168667, 4731.34048645, 933.18903575])

However, if i ask for 100 draws for each element of mu, sigma:

a = np.random.normal(mu, sigma, 100)

a = np.random.normal(mu, sigma, 100)
Traceback (most recent call last):

File "<ipython-input-417-4aadd7d15875>", line 1, in <module>
a = np.random.normal(mu, sigma, 100)

File "mtrand.pyx", line 1652, in mtrand.RandomState.normal

File "mtrand.pyx", line 265, in mtrand.cont2_array

ValueError: shape mismatch: objects cannot be broadcast to a single shape

I have also tried using a tuple for size(s):

s = (100, 100, 100, 100)
a = np.random.normal(mu, sigma, s)

What am i missing?

I don't believe you can control the size parameter when you pass a list/vector of values for the mean and std. Instead, you can iterate over each pair and then concatenate:

np.concatenate(
   [np.random.normal(m, s, 100) for m, s in zip(mu, sigma)]
) 

This gives you a (400, ) array. If you want a (4, 100) array instead, call np.array instead of np.concatenate .

If you want to make only one call, the normal distribution is easy enough to shift and rescale after the fact. (I'm making up a 10000-long vector of mu and sigma from your example here):

mu = np.random.choice([2000., 3000., 5000., 1000.], 10000)               
sigma = np.random.choice([250., 152., 397., 180.], 10000)

a = np.random.normal(size=(10000, 100)) * sigma[:,None] + mu[:,None]

This works fine. You can decide if speed is an issue. On my system the following is just 50% slower:

a = np.array([np.random.normal(m, s, 100) for m,s in zip(mu, sigma)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM