Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: NxM array of samples drawn from NxM normal distributions

I have two 2D arrays (or of higher dimension), one that defines averages (M) and one that defines standard deviations (S). Is there a python library (numpy, scipy, ...?) that allows me to generate an array (X) containing samples drawn from the corresponding distributions?

In other words: each entry xij is a sample that comes from the normal distribution defined by the corresponding mean mij and standard deviation sij.

like image 481
Andrea Avatar asked Mar 19 '16 03:03

Andrea


1 Answers

Yes numpy can help here:

There is a np.random.normal function that accepts array-like inputs:

import numpy as np
means = np.arange(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
stddevs = np.ones(10) # [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

samples = np.random.normal(means, stddevs)
array([-1.69515214, -0.20680708,  0.61345775,  2.98154162,  2.77888087,
        7.22203785,  5.29995343,  8.52766436,  9.70005434,  9.58381479])

even if they are multidimensional:

means = np.arange(10).reshape(2,5) # make it multidimensional with shape 2, 5
stddevs = np.ones(10).reshape(2,5)

samples = np.random.normal(means, stddevs)
array([[-0.76585438,  1.22226145,  2.85554809,  2.64009423,  4.67255324],
       [ 3.21658151,  4.59969355,  6.87946817,  9.14658687,  8.68465692]])

The second one has a shape of (2,5)


In case you want only different means but the same standard deviation you can also only pass one array and one scalar and still get an array with the right shape:

means = np.arange(10)

samples = np.random.normal(means, 1)
array([ 0.54018686, -0.35737881,  2.08881115,  3.08742942,  4.4426366 ,
        3.6694955 ,  5.27515536,  8.68300816,  8.83893819,  7.71284217])
like image 162
MSeifert Avatar answered Nov 08 '22 06:11

MSeifert