Python: Sample from multivariate normal with N means and same covariance matrix

白昼怎懂夜的黑 提交于 2021-02-19 08:14:11

问题


Suppose I want to sample 10 times from multiple normal distributions with the same covariance matrix (identity) but different means, which are stored as rows of the following matrix:

means = np.array([[1, 5, 2],
                  [6, 2, 7],
                  [1, 8, 2]])

How can I do that in the most efficient way possible (i.e. avoiding loops)

I tried like this:

scipy.stats.multivariate_normal(means, np.eye(2)).rvs(10)

and

np.random.multivariate_normal(means, np.eye(2))

But they throw an error saying mean should be 1D.

Slow Example

import scipy
np.r_[[scipy.stats.multivariate_normal(means[i, :], np.eye(3)).rvs() for i in range(len(means))]]

回答1:


Your covariance matrix indicate that the sample are independent. You can just sample them at once:

num_samples = 10
flat_means = means.ravel()

# build block covariance matrix
cov = np.eye(3)
block_cov = np.kron(np.eye(3), cov)

out = np.random.multivariate_normal(flat_means, cov=block_cov, size=num_samples)

out = out.reshape((-1,) + means.shape)


来源:https://stackoverflow.com/questions/65252624/python-sample-from-multivariate-normal-with-n-means-and-same-covariance-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!