hookch
hookch

Reputation: 69

Specify the spherical covariance in numpy's multivariate_normal random sampling

In numpy manual, it is said:

Instead of specifying the full covariance matrix, popular approximations include:  
    Spherical covariance (cov is a multiple of the identity matrix)

Has anybody ever specified spherical covariance? I am trying to make it work to avoid building the full covariance matrix, which is too much memory-consuming.

Upvotes: 2

Views: 1672

Answers (2)

Jaime
Jaime

Reputation: 67427

While @RobertKern's approach is correct, you can let numpy handle all of that for you, as np.random.normal will do broadcasting on multiple means and standard deviations:

>>> np.random.normal(0, [1,2,3])
array([ 0.83227999,  3.40954682, -0.01883329])

To get more than a single random sample, you have to give it an appropriate size:

>>> x = np.random.normal(0, [1, 2, 3], size=(1000, 3))
>>> np.std(x, axis=0)
array([ 1.00034817,  2.07868385,  3.05475583])

Upvotes: 1

Robert Kern
Robert Kern

Reputation: 13430

If you just have a diagonal covariance matrix, it is usually easier (and more efficient) to just scale standard normal variates yourself instead of using multivariate_normal().

>>> import numpy as np
>>> stdevs = np.array([3.0, 4.0, 5.0])
>>> x = np.random.standard_normal([100, 3])
>>> x.shape
(100, 3)
>>> x *= stdevs
>>> x.std(axis=0)
array([ 3.23973255,  3.40988788,  4.4843039 ])

Upvotes: 1

Related Questions